微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

1、获取字符串长度

 
#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、字符串连接

 
#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、字符串比较

 
#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、字符串转字符数组

 
#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语言教程

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐