字符串
输入输出
- 字符串等于字符数组加结束符’\0’,所以字符数组长度要加一
char a1[] = {'c','+','+'}; //列表初始化无空字符
char a2[] = {'c','+','+','\0'}; //含有显示的空字符
char a3[] = {"c++"}; //自动添加结尾空字符
char a4[6] =" Daniel"; //错误!没有空间存放空字符'\0'
-
cin 与 scanf 在读入到 " " 或 ‘\0’ 或 “\n” 时会结束
-
要读入整行字符时需要fgets(s,100,stdin);或 getline(s,100);
-
让字符数组从第n 项输出: a[] +x;
常用操作
-
#include <string.h> 包含:
-
(1)strlen(str) 求字符串长度
-
(2)strcmp(a,b) 比较两个字符串的大小(字典序), a < b 返回-1,a == b返回0,a > b 返回1
-
(3) strcpy(a,b) 将字符串b复制给从a开始的字符数组
-
遍历 : 当成数组
#include <cstdio> #include <iostream> #include <cstring> using namespace std; int main () { char s1[100],s2[100]; scanf("%s",s1); for (int i =0 ; i < strlen (s1); i++) cout << s1[i] << endl; return 0; }
标准库类型 string
- 可变长的字符序列,比字符数组更好用,需要引入: #include
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
string s1; // 默认的空字符串
string s2 = s1; // s2是s1的一个副本
string s3 = "hiya" // s3是该字符串字面值的一个副本
string s4 (10,'c'); //定义10个c
return 0;
}
string 的empty 和 size和相加操作 (注意size 是无符号整数,因此s.size() <= -1 一定成立
- empty >> 空返回 1 否则返回 0
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
string s1 = "abc",s2;
cout << s1.empty() << endl;
cout << s2.empty() << endl;
return 0;
}
-
size 长度
#include <cstdio> #include <iostream> #include <cstring> using namespace std; int main () { string s1 = "abc",s2; cout << s1.size() << endl; cout << s2.size() << endl; return 0; }
本文介绍了C++中字符串的相关操作,包括输入输出、常用函数如strlen、strcmp、strcpy,以及标准库类型`std::string`的特点,强调了`string`的`empty`、`size`方法的使用,并指出其size返回的是无符号整数。
3141

被折叠的 条评论
为什么被折叠?



