Library string type(2)——关于String的操作

关于string的定义,请参阅博文http://blog.csdn.net/larry233/article/details/51483827

string的操作

  • s.empty() //Returns true if s is empty,otherwise returns false

  • s.size() //Returns numbers of characters of s

  • s[n] //Returns the character at position n in s,positions start at 0

  • s1 + s2 //Returns a string equals to the concatenation of s1 and s2
  • s1 = s2 //Replaces characters in s1 by a copy of s2
  • v1 == v2 //Returns true if v1 and v2 are equal,false otherwise
  • !=,<,<=,>,>= //Have their normal meanings

以下为示例代码:

#include<iostream>
#include<string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
    string st("The expense of spirit\n");
    cout<<"The size of "<<st<<"is "<<st.size()
        <<" characters, including the newline"<<endl;
    if(st.size() == 0)
        cout<<"st is empty"<<endl;
    /*
     *equals to:
     *if(st.empty()){...}
     */
     string st1 = st;
     cout<<"st1 is "<<st1;
     return 0;
}

运行结果为:

The size of The expense of spirit is

22 characters, including the newline

st1 is The expense of spirit

如果再插入如下代码:

string s1 = "Hello";
string s2 = " World!\n";
string s3 = s1 + s2;
cout<<s3<<endl;

运行结果为

Hello World!

字符串字面常量与string相加

请看下列代码:

string s1 = "hello";
string s2 = "world";
string s3 = s1 + ","; //ok,adding a string and a literal
strign s4 = "hello" + ",";//error,no string operand
string s5 = s1 + "," + " world";//ok,each + has a string operand
string s6 = "hello" + "," + s2;//error,can't add strign literals

s1和s2都是直接初始化为string的,但是对于s3就不同了,首先“,”是一个字符串字面常量,它与s1相加,由于s1是string,它被隐式转换为string后再与s1相加;
对于s4,两个都是字符串字面常量,它们相加是非法的,必须要用strcat(s1,s2)将它们“连接”,而不是“相加”;
对于s5,其实它和s3是一样的:s1和“,”相加,它先将“,”转换为string再与s1相加,返回的是string,然后再与”world”相加…
对于s6,一开始是”hello”和”,”相加,和s4的错误相同。

string:: size_type

逻辑上来说,string的size()函数的返回值应为int型,更精确的说,是unsigned型。但是在实际应用中,我们从某一个文件读到的字符数量很容易就超过了unsigned型的范围,string为size()函数里提供了一种更为安全的返回类型string:: size_type

从string中取得字符

示例如下:

string str(“some string”);
for(string::size_type ix = 0; ix != str.size(); ++ix)
    cout<<str[ix]<<endl;

也可以改变string的值:

//将str的字符全置为*
for(string::size_type ix = 0; ix != str.size(); ++ix)
    str[ix] = 'x';

作者注:从改变string的值的方式(是str[x] = ‘x’而不是str[x] = “x”)我们可以看出,我们所得到的每一个str的字符都是char型,而不是string。这是值得注意的。

处理string字符串的函数

处理string字符串的函数包含在头文件cctype中,编程时应将该头文件包含:

#include<cstring>

该头文件包含的一部分函数清单如下:
这里写图片描述

// 本文所有代码均出自《C++ primer》

// 上次敲英文敲得太累了,这次直接翻译成中文了(其实真正的原因是英文版没人看,赚不到访问量: ( ),结果还是花了将近两个小时,天哪我还没复习啊。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值