cpp教程9-C++中的字符串操作

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值