返回字符串的长度
- string标准库
#include<iostream> #include<cstring> using namespace std; int main() { string s="abc"; cout<<s.size()<<endl; return 0; }
- C风格字符串函数
#include<stdio.h> #include<string.h> int main() { char s[]="abc"; printf("%d ",strlen(s)); return 0; }
字符串的比较:
- 标准string
string s1="A string example"; string s2=“A different string”; if(s1<s2) { //////////// } else { /////// }
- C风格字符串
const char s1="A string example"; const char s2="A different string"; if(strcmp(s1,s2)<0) { ////////// } else { ///////// }
连接字符串:
- 标准库string
string s1="abc"; string s2="de"; string largestr=s1 + " " + s2;
- C风格函数
const char s1[]="abc"; const char s2[]="de"; const char largestr[100]; strcpy(largestr,s1); strcat(largestr," "); strcat(largestr,s2);
注意:这里的字符串数组largestr要有足够大的内存空间
拷贝和赋值:
- 标准库string
string s1="abc"; string s2=s1;
- C风格函数
int a[]={0,1,2}; int b[]=a;//错误:不允许使用一个数组初始化另一数组 a2=a; //错误:不能把一个数组直接赋值给另一数组
注意:传入C风格函数的指针必须指向以空字符作为结束的数组。