What are the common methods of string class in C++

王林
Release: 2020-05-13 11:58:05
Original
6388 people have browsed it

What are the common methods of string class in C++

#The common methods of string class in c are as follows:

1. Get the string length

 
#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;
}
Copy after login

2. String connection

 
#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;
}
Copy after login

3. String comparison

 
#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;
}
Copy after login

4. Convert string to character array

 
#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;
}
Copy after login

Recommended tutorial: c language tutorial

The above is the detailed content of What are the common methods of string class in C++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template