C++string类总结

一、string的初始化

首先,为了在程序中使用string类型,必须包含头文件 <string>。如下:

   #include <string>

注意string.h,string.h是C字符串头文件。

string类位于名字空间std中的模板类,使用时可以使用std::string,但通常为方便使用还需要增加:

#include <iostream>   
using namespace std;

声明一个字符串变量很简单:

string str;

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>


using namespace std;


int main ()
{
    string str;  //定义了一个空字符串str
    str = "Hello world!!!";   // 给str赋值为"Hello world!!!"
    char cstr[] = "abcde";  //定义了一个C字符串
    string str1(str);       //调用复制构造函数生成str1,str1为str的复制品
    cout << str1 << endl;
    string str2(str,6);     //将str内,开始于位置6的部分当作str2的初值
    cout << str2 << endl;
    string str3(str,2,3);  //将str内,开始于2且长度顶多为3的部分作为s3的初值
    cout << str3 <<endl;
    string str4(cstr);   //将C字符串作为s4的初值
    cout << str4 << endl;
    string str5(cstr,4);  //将C字符串前4个字符作为字符串str5的初值。
    cout << str5 << endl;
    string str6(5,'B');  //生成一个字符串,包含5个'B'字符
    cout << str6 << endl;
    string str7(str.begin(),str.begin() + 6); //区间str.begin()和str.begin()+6内的字符作为初值
    cout << str7 << endl;
    return 0;
}

 

程序执行结果为:

Hello world!!!
world!!!
llo
abcde
abcd
BBBBB
Hello

二、string的比较等操作

你可以用 ==、>、<、>=、<=、和!=比较字符串,可以用+或者+=操作符连接两个字符串,并且可以用[]获取特定的字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>


using namespace std;


int main()
{
    string str;


    cout << "Please input your name:" << endl;
    cin >> str;
    if( str == "Chen" )   // 字符串相等比较
    {
        cout << "you are Chen!" << endl;
    }
    else if( str != "Wang" )  // 字符串不等比较
    {
        cout << "you are not Wang!" << endl;
    }
    else if( str < "Chen")     // 字符串小于比较,>、>=、<=类似
    {
         cout << "your name should be ahead of Chen" << endl;
    }
    else
    {
        cout << "your name should be after of Chen"<<endl;
    }
    str += ", Welcome!";  // 字符串+=
    cout << str << endl;
    for(unsigned int i = 0 ; i < str.size(); i++)
    {
        cout << str[i];  // 类似数组,通过[]获取特定的字符
    }
    return 0;
}

 

程序执行结果为:

Please input your name:

Zhang
you are not Wang!
Zhang, Welcome!

Zhang, Welcome!

上面代码中的cout << str[i]; 可以替换为cout << str.at(i);(使用at会进行是否越界检查,str.at(i)和str[i]含义一样,但是由于at会进行边界检查,花费的时间会偏长)。

三、string特性描述

可用下列函数来获得string的一些特性:

int capacity()const;    //返回当前容量(即string中不必增加内存即可存放的元素个数)
int max_size()const;    //返回string对象中可存放的最大字符串的长度
int size()const;        //返回当前字符串的大小
int length()const;       //返回当前字符串的长度
bool empty()const;        //当前字符串是否为空
void resize(int len,char c);  //把字符串当前大小置为len,多去少补,多出的字符c填充不足的部分

测试代码:

#incl ude <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    if (str.empty()) //判断字符串是否为空
    {
         cout << "str is NULL." << endl;
    }
    else
    {
        cout << "str is not NULL." << endl;
    }

    str = str + "1234abc";
    cout << "str is " << str << endl;
    cout << "str's size is " << str.size()<<endl;
    cout << "str's capacity is " << str.capacity() << endl;
    cout << "str's max size is " << str.max_size() << endl;
    cout << "str's length is " << str.length() << endl;
    str.resize(20,'a');
    cout << "str is " << str << endl;
    str.resize(5);
    cout << "str is " << str << endl;
    return 0;
}

程序执行结果为:

str is NULL.
str is 1234abc
str's size is 7
str's capacity is 7
str's max size is 1073741820
str's length is 7
str is 1234abcaaaaaaaaaaaaa
str is 1234a

四、string的查找

由于查找是使用最为频繁的功能之一,string提供了非常丰富的查找函数:

size_type find( const basic_string &str, size_type index );  //返回str在字符串中第一次出现的位置(从index开始查找),如果没找到则返回string::npos
size_type find( const char *str, size_type index );  // 同上
size_type find( const char *str, size_type index, size_type length );  //返回str在字符串中第一次出现的位置(从index开始查找,长度为length),如果没找到就返回string::npos
size_type find( char ch, size_type index );  // 返回字符ch在字符串中第一次出现的位置(从index开始查找),如果没找到就返回string::npos

注意:判断字符串是否找到根据string::npos进行判断,例如查找字符串A是否包含子串B,用得死strA.find(strB) != string::npos,而不是strA.find(strB) > 0。为什么可以再博客weibo100找到。

先看下面的代码

int idx = str.find("abc");
if (idx == string::npos);

  上述代码中,idx的类型被定义为int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。npos 是这样定义的: static const size_type npos = -1; 因为 string::size_type (由字符串配置器 allocator 定义) 描述的是 size,故需为无符号整数型别。因为缺省配置器以型别 size_t 作为 size_type,于是 -1 被转换为无符号整数型别,npos 也就成了该型别的最大无符号值。不过实际数值还是取决于型别 size_type 的实际定义。不幸的是这些最大值都不相同。事实上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是两者型别大小不同)。因此,比较式 idx == string::npos 中,如果 idx 的值为-1,由于 idx 和字符串string::npos 型别不同,比较结果可能得到 false。因此要想判断 find()等查找函数的结果是否为npos,最好的办法是直接比较。

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<string>


using namespace std;


int main()
{
    int loc;
    string s = "This is a good day, I am very happy!!!I am very happy!!!, day day up";
    loc = s.rfind("happy",10);
    cout << "the word happy is at index" << loc << endl; //-1表示没找到
    loc = s.rfind("happy");//缺省状态下,从最后一个往前找
    cout << "the word happy is at index" << loc << endl;
    loc = s.find_first_of("day");
    cout << "the word day(first) is at index " << loc << endl;
    loc = s.find_first_not_of("day");
    cout << "the first word not of study is at index" << loc << endl;
    loc = s.find_last_of("day");
    cout << "the last word of day is at index" << loc << endl;
    loc = s.find("day");//缺陷状态下从第一个往后找
    cout << loc;
    return 0;
}

运行结果:

 the word happy is at index-1
the word happy is at index48
the word day(first) is at index 8
the first word not of study is at index0
the last word of day is at index64
15

五、其他常用函数

string &insert(int p,const string &s);  //在p位置插入字符串s
string &replace(int p, int n,const char *s); //删除从p开始的n个字符,然后在p处插入串s
string &erase(int p, int n);  //删除p开始的n个字符,返回修改后的字符串
string substr(int pos = 0,int n = npos) const;  //返回pos开始的n个字符组成的字符串
void swap(string &s2);    //交换当前字符串与s2的值
string &append(const char *s);   //把字符串s连接到当前字符串结尾
void push_back(char c)   //当前字符串尾部加一个字符c
const char *data()const;   //返回一个非null终止的c字符数组,data():与c_str()类似,用于string转const char*其中它返回的数组是不以空字符终止,
const char *c_str()const;  //返回一个以null终止的c字符串,即c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同,用于string转const char*

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main()
{
    string str1 = "abcd1234defg";
    string str2 = "swap!";
    cout << str1 << endl;
    cout << str1.erase(4,4) << endl;  //从索引4开始的4个字符,即删除掉了"1234"
    cout << str1.insert(0,"123") << endl; //在头部插入
    cout << str1.append("123") << endl;   //append()方法可以添加字符串
    str1.push_back('A');  //push_back()方法只能添加一个字符
    cout << str1 << endl;
    cout << str1.replace(0,3,"hello") << endl; //即将索引0开始的3个字符替换成"hello"
    cout << str1.substr(5,7) << endl; //从索引5开始7个字节
    str1.swap(str2);
    cout << str1 << endl;
    const char* p = str1.c_str();
    printf("%s\n",p);
    return 0;
}

 

程序执行结果为:

abcd1234defg
abcddefg
123abcddefg
123abcddefg123
123abcddefg123A
helloabcddefg123A
abcddef
swap!
swap!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值