//一直都想把字符串操作常用的函数总结一些,不全但重在积累;
字符串的比较:
语法:
int compare( const basic_string &str ); int compare( const char *str ); int compare( size_type index, size_type length, const basic_string &str ); int compare( size_type index, size_type length, const basic_string &str, size_type index2, size_type length2 ); int compare( size_type index, size_type length, const char *str, size_type length2 ); |
compare()函数以多种方式比较本字符串和str,返回:
返回值 | 情况 |
---|---|
小于零 | this < str |
零 | this == str |
大于零 | this > str |
不同的函数:
- 比较自己和str,
- 比较自己的子串和str,子串以index索引开始,长度为length
- 比较自己的子串和str的子串,其中index2和length2引用str,index和length引用自己
- 比较自己的子串和str的子串,其中str的子串以索引0开始,长度为length2,自己的子串以index开始,长度为length
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string s,str;
cin>>s>>str;
cout<<s.compare(str)<<endl;//相等为0,s<str ----》值为-1,否则为1;
cout<<s.compare(0,2,str)<<endl;
return 0;
}
字符串带空格、Tab的输入:
语法:
istream &getline( char *buffer, streamsize num ); istream &getline( char *buffer, streamsize num, char delim ); |
getline()函数用于输入流,读取字符到buffer中,直到下列情况发生:
- num - 1个字符已经读入,
- 碰到一个换行标志,
- 碰到一个EOF,
- 或者,任意地读入,直到读到字符delim。delim字符不会被放入buffer中。
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string s,str;
getline(cin,str);
cin>>s;
cout<<str<<endl;
cout<<s<<endl;
return 0;
}
字符串或字符数组的大小写转换:
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main( )
{
string s="abcdef";
string str="AbCDe";
//transform()只适合字符串
transform(s.begin(),s.end(),s.begin(),::toupper);//转换为大写
transform(str.begin(),str.end(),str.begin(),::tolower);//转换为小写
cout<<s<<endl;
cout<<str<<endl;
//字符数组的大小写转换函数
char s1[10]={'a','B','d','R','g','H','s',};
strlwr(s1);
cout<<s1<<endl;
strupr(s1);
cout<<s1<<endl;
return 0;
}
两个字符串的交换函数 swap( ):
代码:
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string first="This comes first" ;
string second="And this is second" ;
first.swap( second );
cout<<first<<endl;
cout<<second<<endl;
return 0;
}
返回字符串的长度
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin,s);
char chr[6]={'a','b','c'};
cout<<strlen(chr)<<endl;//只适用于字符数组
cout<<s.length()<<endl;//只适用于字符串
return 0;
}