C++中的字符串操作
C++字符串的操作是不太方便的,
字符串与数字的互相转换
数字转string
string并没有提供构造方法来直接数字转换成字符串, 比如 string(int), string(double) 之类的.
头文件:string.h
std::to_string(int)
std::to_string(long)
std::to_string(long long)
std::to_string(float)
std::to_string(double)
std::to_string(long double)
string转数字
头文件:cstdlib
std::stoi
std::stol
std::stoll
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num=0;
string str="123";
num=stoi(str);
cout<<num<<endl;
return 0;
}
split
string 自己是没有提供这个方法的,只有靠自己实现, 我把自己的的实现方法分享给大家.
vector<string> splitx(const string& s, const string& spitter){
vector<string> ret; // 1
int p1 = 0;
int p2;
int len = spitter.size();
int slen = s.size();
while(true){
p2 = s.find(spitter, p1);
if(p2 == string::npos) p2 = slen;
ret.push_back(s.substr(p1, p2-p1));
p1 = p2+len;
if(p1>slen) break;
}
return ret;
}
// 测试
void test_splitx(){
string s1 = "1 2 3 4 56";
string spliter = string(" ");
vector<string> aa = splitx(s1, spliter);
for(string s: aa){
cout << s << endl;
}
print("abc"+to_string(124) ); // print是我自己封装的方法,不是标准库里的!
}
C语言中的一点字符串操作
是一个面向过程的语言
strcat()函数:连接字符串
char* ,char*
char* str1 = “Hello”;
char*str2 = “World”;
//方式一
char str3[20];
strcpy(str3, str1);
strcat(str3, str2);
//方式二
//char str3[20];
sprintf(str3,"%s%s",str1,str2);
string,string
string str1= “Hello”;
string str2 = “World”;
string str3 =str1+str2;
char*, string
char* str1 = “Hello”;
string str2 = “World”;
string str3=str1;
str3=str3+str1;
总结
C++的字符串真是太烂了…标准库的工具太少了.
想念Java和Python的字符串操作!
参考
[1]C++数字转string,string转数字函数总结
https://blog.csdn.net/salmonwilliam/article/details/87868263
[2]C++常见问题: 字符串分割函数 split
https://www.cnblogs.com/dfcao/p/cpp-FAQ-split.html
[3]C语言strcat()函数:连接字符串
http://c.biancheng.net/cpp/html/160.html