比较常用的几个字符串处理方法:
1.字符串拼接 strcat
2.判断字符串是否相等 strcmp/ strcasecmp
3.字符串复制strcpy
4.获取字符串长度 strnlen
------------------------------------------------------------------------------
#include <iostream> #include <string.h> #include <fstream> using namespace std; int main() { char a[] = "我要"; char b[] = "KK"; char *site; //1.字符串拼接 site = strcat(a,b); cout<<"输出拼接的字符串:"<<site << endl; //2.判断字符串是否相等 //2.1 strcmp 判断字符串是否相等 char *str1; if(strcmp(a,b)==0){ cout<<"strcmp a=b : ture"<< endl; }else{ cout<<"strcmp a!=b : false"<< endl; } //2.2 strcasecmp 判断字符串是否相等 char *c = "you"; char *d = "you"; if(strcasecmp(c,d)==0){ cout<<"strcasecmp c=d : ture"<< endl; }else{ cout<<"strcasecmp c!=d: false"<< endl; } //strcpy()函数:是将一个字符串复制到另一块空间地址中 的函数,‘\0’是停止拷贝的终止条件,同时也会将 '\0' 也复制到目标空间。下面是库中的strcpy()函数声明: //char* strcpy(char* destination,const char* source); //1. 函数的参数: //char* destination---------目标字符串的首地址 //const char* source------源地址:被复制的字符串的首地址,用const修饰,避免修改掉被拷贝的字符串 //3.将一个字符串复制到另一块空间地址中(会覆盖目标地址原有的值) char e[] = "c123a"; char *f= "d456b"; strcpy(e,f); cout<< e << " --- "<<f<<endl; //4.strlen 获取字符串长度 char *h = "abcdefghigkl"; int n = strlen(h); cout<<"长度=" << n <<endl; //5.strnlen 获取字符串长度 //获取字符串s中实际字符个数,不包括结尾的'\0';如果实际个数 <= maxlen,则返回n,否则返回第二个参数 cout<<strnlen(h, 10)<<endl; char arr1[10] = "abasfsdfs"; char arr2[10] = "abcd"; printf("%s\n", strcpy(arr1, arr2)); return 0; }