首先,為了在我們的程序中使用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";