c++中string类的常用方法有哪些


本文摘自PHP中文网,作者V,侵删。

c++中string类的常用方法如下:

1、获取字符串长度

1

2

3

4

5

6

7

8

9

10

11

12

#include<cstdio>

#include<iostream>

#include<string>

using namespace std;

int main()

{

    string str1 = "hello";

  

    int length = str1.length();

    printf("调用str.length()函数获取字符串长度:%d\n\n",length );

    return 0;

}

2、字符串连接

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include<cstdio>

#include<iostream>

#include<string>

using namespace std;

int main()

{

    string str1 = "hello";

    string str2="my girl!";

    string str3="hello ";

  

    string str4=str1+str2;

    string str5=str3+str2;

    cout<<"字符串str1+str2连接结果:"<<str4<<endl;

    cout<<endl;

    cout<<"字符串str3+str2连接结果:"<<str5<<endl;

    return 0;

}

3、字符串比较

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include<cstdio>

#include<iostream>

#include<string>

using namespace std;

int main()

{

    string str1 = "hello";

    string str2="my girl!";

    string str3="hello ";

  

    if (str1 < str3)

        cout << "字符串比较结果:" << "str1<str2" << endl;

    cout << endl;

    return 0;

}

4、字符串转字符数组

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#include<cstdio>

#include<iostream>

#include<string>

#include<cstring>

using namespace std;

int main()

{

    string str1 = "hello";

    string str2="my girl!";

    string str3="hello ";

  

    char *d = new char[20];  //因为下一句那里不是直接赋值,所以指针类型可以不用const char *

    strcpy(d, str3.c_str());  //c_str 取得C风格的const char* 字符串

    cout << "str3:" << c << endl;

    cout << "d:" << d << endl;

    str3 = "hahaha";

    cout << "str3:" << c << endl;

    cout << "d:" << d << endl;

    return 0;

}

推荐教程:c语言教程

以上就是c++中string类的常用方法有哪些的详细内容!

相关阅读 >>

C++中类的定义是什么

C++ 引用和指针区别

dev C++怎么用

c语言 三种求回文数的算法

浅谈C++生成guid的两种方法

技术解答面向对象的初步认识(C++ 类)

基于汇编的 c/C++ 协程(用于服务器)的实现

C++)错误的map删除操作和stl中容器的迭代器的底层实现机制

在c/C++中如何使用extern关键字

C++ 判断本机是否有.net环境

更多相关阅读请进入《C++》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...