C/C++字符串学习

最近做项目时,碰到一些字符串的问题,还是不是很熟悉。说明基础薄弱,要对字符串的使用进行总结。

 

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中间的格式可以自己定 加个空格啊 或者输入其他提示的字符。

 

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值