c++字符串使用

    首先,为了在我们的程序中使用string类型,我们必须包含头文件<string>。如下:#include<cstring>//注意这里不是string.h首先,为了在我们的程序中使用string类型,我们必须包含头文件<string>。如下:#include<cstring>//注意这里不是string.h。

  1.strlen 函数

strlen 函数将接收一个 C 字符串作为实参,并返回字符串的长度

例如:

  char str[] = "Hello";
  int length = strlen(str);

length=5.

  2.strcat 函数

strcat 函数釆用两个字符串作为形参并连接它们,返回由第一个字符串和第二个字符串的所有字符组成的单个字符串

例如:const int SIZE = 13;char string1[SIZE] = "Hello ";char string2 [ ] = "World!";

           cout << string1 << endl;

           cout << string2 << endl;strcat(string1, string2);

           cout << string1 << endl;

输出结果是:

Hello
World!
Hello World!

  3.strcpy 函数

strcpy 函数可以用来将一个字符串复制到另一个字符串中

例如:char string1 [ ] = "Hello ";

           cout << string1 << endl;

           strcpy(string1, "World!");

           cout << string1;

输出结果:

Hello
World!

  4.strcmp 函数

strcmp函数以两个 C 字符串作为形参,并返回一个整数,表示两个字符串相互比较的结果

例如:if (strcmp(stringl, string2) == 0)

           cout << "The strings are equal";

           else

           cout << "The strings are not equal";

相等输出"The strings are equal";不等:"The strings are not equal";

 

posted @ 2019-04-26 23:03  严德怀  阅读(1343)  评论(0编辑  收藏  举报