字符串

子淼
发布于 2024-01-22 / 87 阅读
0
0

字符串

char类型字符串

//头文件
#include<cstring>
//创建字符串
char a[101];
//输入不带空格字符串
cin >> a;
//输入带空格字符串
cin.getline(a,101);
//求字符串长度
int l = strlen(a);

 

char字符串常用函数

函数

功能

int l = strlen(a)

用l存储字符a的长度

strcpy(a,b)

把b赋值给a

strcat(a,b)

把b接在a后面

k=strcmp(a,b)

字典序比较

k=1 a大于b

k=0 a等于b

k=-1 a小于b

//示例
#include <iostream>
#include <cstring>
using namespace std;
int main (){
   char s1[15] = "zimiao";
   char s2[15] = "biancheng";
   char s3[15];
   // 复制 s1 到 s3
   strcpy(s3, s1);
   cout << "strcpy( s3, s1) : " << s3 << endl;
 
   // 连接 s1 和 s2
   strcat(s1, s2);
   cout << "strcat( s1, s2): " << s1 << endl;
 
   // 连接后,s1 的总长度
   int l = strlen(s1);
   cout << "strlen(s1) : " << l << endl;
 
   //比较 s1 和 s2 的字典序
   if(strcmp(s1, s2)==1){
      cout << "s1大于s2";
   }else if(strcmp(s1, s2)==0){
      cout << "s1等于s2";
   }else{ // == -1
      cout << "s1小于s2";
   }
   return 0;
}

string类型字符串

//头文件
#include<string>
//创建变量
string s;
//输入不带空格字符串
cin >> s;
//输入带空格字符串
getline(cin,s);
//求长度
int l = s.length();
int l = s.size();

string字符串的基本操作

#include <iostream>
#include <string>
using namespace std; 
int main (){
   string s1 = "zimiao";
   string s2 = "biancheng";
   string s3;
   // 复制 s1 到 s3
   s3 = s1;
   cout << "s3: " << s3 << endl;
 
   // 连接 s1 和 s2
   s3 = s1 + s2;
   cout << "s1 + s2: " << s3 << endl;
 
   // 连接后,s3 的总长度
   int l = s3.size();
   cout << "s3.size() :  " << l << endl;


   //比较 s1 和 s2 大小
   if(s1 > s2){
     cout << "s1大于s2" << endl;
   }
   return 0;
}

注意事项

  1. 如果先有cin,后有getline

注意:
如果想要实现先用cin输入,然后在输入一行带空格字符串
cin >> n;
cin.getline(a,101);
这样写字符无法被获取到,因为输入完n后按的回车会被cin.getline拿到
解决方法:
cin >> n;
cin.ignore();//抵消掉一个 \n
cin.getline(a,101);
  1. 字符串默认从下标0开始

#include<iostream>
using namespace std;
int main(){
	string s;
	cin >> s;
	int l = s.length();
	for(int i=0;i<l;i++){
		cout << s[i] << " ";
	}
	return 0;
}
  1. string类型不能用scanf()和printf(),因为string是C++独有的。

  2. 使用scanf()输入带空格字符串

#include<iostream>
using namespace std;
int main(){
	char a[101];
	scanf("%[^\n]",a);
	printf("%s",a);
	return 0;
}


评论