最近做项目时,碰到一些字符串的问题,还是不是很熟悉。说明基础薄弱,要对字符串的使用进行总结。
1.字符串初始化
常用的字符串的初始化三种
#include <iostream>
using namespace std;
int main() {
string s1 = "hello world";
string s2 = s1;
string s3(s1);
cout<<"s1 value is "<<s1<<endl;
cout<<"s2 value is "<<s2<<endl;
cout<<"s3 value is "<<s3<<endl;
return 0;
}
这三种复制都是可以的,这里的输出都是一样的结果。
2.字符串比较
在C++中是可以比较两个字符串大小的,有两种方法。
- 一种是直接用 "==" 来判断
- 还有一种用自带的函数compare来判断
#include <iostream>
using namespace std;
int main() {
string s1 = "hello world";
string s4 = "nihao world";
string s5 = "nihaoworld";
cout<<"s1 and s2 "<< (s1 == s2)<<endl;
cout<<"s1 and s3 "<< (s1 == s3)<<endl;
cout<<"s2 and s3" << (s2 == s3)<<endl;
cout<<"s1 and s4" << (s1 == s4)<<endl; //0
cout<<"s4 and s5" << (s4 == s5)<<endl; //0
return 0;
}
#include <iostream>
using namespace std;
int main() {
string s1 = "hello world";
string s2 = s1;
string s3(s1);
cout<<"s1 and hello world "<<!s1.compare("hello world")<<endl;
cout<<"s1 and s2 "<<!s1.compare(s2)<<endl;
return 0;
}
compare比较要取反,相同为0 不同为1。
3.字符串连接
字符串连接有很多种方法,说一些常用的。
3.1用 "+"来连接
#include <iostream>
using namespace std;
int main() {
string s1 = "hello world";
string s2 = "zaoshanghao";
string s4,s5;
s4 = s1 + s2;
s5 = s1 + " " + s2;
cout<<"s4 value is "<<s4<<endl;
cout<<s5<<endl;
}
可以连续+来拼接。
3.2用strcat()来拼接
#include <stdio.h>
#include <string.h>
int main ()
{
char str[80];
strcpy (str,"hello ");
strcat (str,"world ");
puts (str);
return 0;
}
3.3用sprintf()来拼接
注意在C++中不能这么写
char *first = "HEllo";
这是会报警告的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *first = (char *)"Hello";
char *last = (char *)"World";
char *s = (char *) malloc(strlen(first) + strlen(last));
sprintf(s, "%s %s", first, last);
printf("%s\n",s);
return 0;
}
sprintf中间的格式可以自己定 加个空格啊 或者输入其他提示的字符。