【C++注意事项】6 Library string Type

Processing Every Character? Use Range-Based for

If we want to do something to every character in a string, by far the best approach is to use a statement introduced by the new standard: the range for statement. This statement iterates through the elements in a given sequence and performs some operation on each value in that sequence. The syntactic form is

for( declaration: expression)
    statement

where expression is an object of a type that represents sequence, and declaration defines the variable that we’ll use to access the underlying elements in the sequence. On each iteration, the variable in declaration is initialized from the value of the next element in expression.

A string represents a sequence of characters, so we can use a string as the expression in a range for. As a simple example, we can use a range for to print each character from a string on its own line of output:

string str("some string");
// print the characters in str one character to a line
for(auto c: str)  // for every char in str
    cout<< c << endl;  // print the current character followed by a newline

The for loop associates the variable c with str. We define the loop control variable the same way we do any other variable. In this case, we use auto to let the compiler determine the type of c, which in this case will be char. On each iteration, the next character in str will be copied into c. Thus, we can read this loop as saying, “For every character c in the string str,” do something. The “something” in this case is to print the character followed by a newline.

As a somewhat more complicated example, we’ll use a range for and the inpunct function to count the number of punctuation characters in a string:

string s("Hello World!!!");
// punct_cnt has the same type that s.size returns
decltype(s.size()) punct_cnt= 0;
// count the number of punctuation charaters in s
for(auto c: s)  // for every char in s
    if(ispunct(c))  // if the character is punctuation
        ++punct_cnt;  // increment the punctuation counter
cout<< punct_cnt
    << " punctuation characters in "<< s << endl;

The output of this program is

3 puctuation characters in Hello World!!!

Here we use decltype( if you want more message, just go to there:The auto and decltype Type Specifier ) to declare our counter.

Using s Subscript for Random Access

In the previous example we advanced our subscript one position at a time to capitalize each character in sequence. We can also calculate an subscript and directly fetch the indicated character. There is no need to access characters in sequence.

As an example, let’s assume we have a number between 0 and 15 and we want to generate the hexadecimal representation of that number. We can do so using a string that is initialized to hold the 16 hexadecimal “digits”:

const string hexdigits= "0123456789ABCDEF";  // possible hex digits
cout<< "Enter a series of numbers between 0 and 15"
    << " separated by spaces. Hit ENTER when finished: "
    << endl;
string result;  // will hold the  resulting hexify‘d string
string::size_type n;  // hold numbers from the input
while(cin>>n)
    if(n < hexdigits.size())  // ignore invalid input
        result+= hexdigits[n];  // fetch the indicated hex digit
cout<< "You hex number is: "<< result << endl; 

If we give this program the input

12 0 5 15 8 15

the output will be

Your hex number is: C05F8F

Whenever we use a subscript, we should think about how we know that it is in range. In this program, our subscript, n, is a string::size_type, which as we know is an unsigned type. As a result, we know that n is guaranteed to be greater than or equal to 0. Before we use n to subscript hexdigits, we verify that it is less than the size of hexdigits.

时间: 2024-11-10 07:33:55

【C++注意事项】6 Library string Type的相关文章

string Type

Notes from C++ Primer Operations Operations of string support lots of operations of sequential container. string s;          define a new empty string object, named s. string s(cp);    define a new string object, initialized by a C-style string point

【C++注意事项】7 Library vector Type

List Initializer or Element Count? In a few cases, what initialization means depends upon whether we use curly braces or parentheses to pass the initializer(s). For example, when we initialize a vector< int > from a single int value, that value migh

Excel Sheet Column Title (STRING - TYPE CONVERTION)

QUESTION Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB FIRST TRY class Solution { public: string convertToTitle(int n) { int r

[C++] String Basic

Namespace Declarations A using declaration let us use a name from a namespace without qualify the name with a namespace_name:: prefix. // using namespace::name using std::vector using std::string  A sperate using declaration is required for each name

nomasp 博客导读:Android、UWP、Algorithm、Lisp(找工作中……

Profile Introduction to Blog 您能看到这篇博客导读是我的荣幸.本博客会持续更新.感谢您的支持.欢迎您的关注与留言.博客有多个专栏,各自是关于 Android应用开发 .Windows App开发 . UWP(通用Windows平台)开发 . SICP习题解 和 Scheme语言学习 . 算法解析 与 LeetCode等题解 .而近期会加入的文章将主要是算法和Android.只是其他内容也会继续完好. About the Author 独立 Windows App 和

C++primer学习笔记(一)——Chapter 3

3.1 Namespace using Declarations 1.因为C++里有名字空间的定义,例如我们使用cin的时候必须写成std::cin,如果就用一次还是可以接受的,但是如果一直都这样,那就很麻烦了.所以C++使用了一个姓的关键字using. (1)第一种用法: 例如:using namespace std; 这样子的话就可以使用std名字空间下面所有的方法而不用加std::. (2)第二种用法: 例如:using std::cin; 这样子的就只能cin前面不加std::,而其他的

C++学习书籍推荐《C++ Primer 第五版 (英文)》下载

百度云及其他网盘下载地址:点我 编辑推荐 <C++ Primer(英文版)(第5版)>是全球最畅销的C++图书.这本久负盛名的C++经典教程,时隔八年之久,终迎来的重大升级.除令全球无数程序员从中受益,甚至为之迷醉的--C++大师Stanley B. Lippman的丰富实践经验,C++标准委员会原负责人Josée Lajoie对C++标准的深入理解,以及C++先驱Barbara E.Moo在C++教学方面的真知灼见外,更是基于全新的C++11标准进行了全面而彻底的内容更新.非常难能可贵的是,

关于创建Android Library所需要知道的一切

关于创建Android Library所需要知道的一切 Android 库(Library)在结构上与 Android 应用模块相同.应用模块所可以包含的东西,在库中都允许存在,包括代码文件.资源文件和manifest文件等. 应用模块编译后生成的是一个apk文件,可以直接在设备上运行,但是,库模块编译后生成的是一个Android Archive文件,简称AAR.AAR文件无法像apk文件一样直接在设备上运行,我们一般用它作为Android app的依赖. 普通JAR文件只能包含代码文件和清单文

关于创建Android Library所须要知道的一切

关于创建Android Library所须要知道的一切 Android 库(Library)在结构上与 Android 应用模块同样.应用模块所能够包括的东西.在库中都同意存在,包括代码文件.资源文件和manifest文件等. 应用模块编译后生成的是一个apk文件,能够直接在设备上执行,可是,库模块编译后生成的是一个Android Archive文件,简称AAR. AAR文件无法像apk文件一样直接在设备上执行,我们一般用它作为Android app的依赖. 普通JAR文件仅仅能包括代码文件和清