【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-10-07 19:20:32

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

c++-C++字符串问题,char type[10]跟string type 有什么区别?

问题描述 C++字符串问题,char type[10]跟string type 有什么区别? 这是在刘汝佳的书上的一道例题,我做的时候遇到了一个问题,我是新手,请指点. #include using namespace std; int m,n; int a[100000+10]; int main(){ int shift_circular_left(int,int); int shift_circular_right(int,int); int find(int); cin>>m>&

【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

&lt;font color=&quot;red&quot;&gt;[置顶]&lt;/font&gt;

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

【软妹带你学技术】Duang!C++那些不得不说的事儿

艾瑞宝迪看过来!(偷偷唱起来了什么鬼......)话说今天,阳光明媚风景如画,正是畅所欲言夸夸其谈的好日子哇,所以,咱们聊聊C++可否?品一杯茶,执一支笔,45°仰望沉思(很好,装叉技能开启).所谓C++,那可是编程语言中的大大大大咖,无人不知无人不晓,放之四海Duang力无敌.然而,还是有一些不得不说的事儿需要告知各位兄台,请耐下心来听我细细道来. [C++注意事项一]数据类型及类型转换 本篇中咱们讨论如何选择类型和类型转换的问题. 如何选择类型呢? 1.当数值不可能为负时,选择无符号类型:

Java String的常用方法及使用注意事项

一.Java String的常用方法: split()方法: equals()方法: substring()方法: 示例方法: private boolean isSameSelCode(Fbillconfirm fbillconfirm, HashMap outputParam){ String strExpenseID=new String(); Fbillconfirmdetail[] fbillconfirmdetail=fbillconfirm.getFbillconfirmdetai

Get the Mime Type from a File

原文:http://www.rgagnon.com/javadetails/java-0487.html Using javax.activation.MimetypesFileTypeMap activation.jar is required, it can be downloaded from http://java.sun.com/products/javabeans/glasgow/jaf.html. The MimetypesFileMap class is used to map

josn字符串-怎么获取type为2的后面的所有电力公司name和code

问题描述 怎么获取type为2的后面的所有电力公司name和code [{"code":"D1_3600","name":"电费缴纳","type":"2","categories":[{"code":"D1_3600_8401","name":"合肥供电公司"},{"code&

对String进行类型验证的帮助类

在工作中经常会遇到 验证String 中的值是否属于Int型或者是Bool又或是Date 一般的做法是用方法 类型.TryParse(string,类型) 来做验证. string strValue = "123"; int intValue; bool isInt = int.TryParse(strValue, out intValue); 但是使用此方法需要创建一个该类型的变量.我工作中写的是WEB程序经常一个页面要验证来自前台的值类型有10几个,这样就略显有点麻烦了. 因为我们

请别再拿“String s = new String(&amp;quot;xyz&amp;quot;);创建了多少个String实例”来面试了吧

这帖是用来回复高级语言虚拟机圈子里的一个问题,一道Java笔试题的. 本来因为见得太多已经吐槽无力,但这次实在忍不住了就又爆发了一把.写得太长干脆单独开了一帖. 顺带广告:对JVM感兴趣的同学们同志们请多多支持高级语言虚拟机圈子  以下是回复内容.文中的"楼主"是针对原问题帖而言. =============================================================== 楼主是看各种宝典了么--以后我面试人的时候就要专找宝典答案是错的来问,方便筛人