一、字符串基礎知識
在C++中,字符串是一串以null字符(\0)結尾的字符序列,也就是一個字符數組。
#include <iostream> #include <cstring> using namespace std; int main() { char str[20] = "Hello"; cout << strlen(str) << endl; //輸出5,因為"Hello"長度為5 return 0; }
上述代碼中,我們使用了頭文件cstring,其中函數strlen可以返回一個字符串的長度。
字符串是一個字符數組,因此可以使用下標訪問、遍歷。
#include <iostream> #include <cstring> using namespace std; int main() { char str[20] = "Hello"; for(int i=0; i<strlen(str); i++) { cout << str[i] << endl; //遍歷輸出每一個字符 } return 0; }
二、字符串拼接
字符串拼接指將兩個字符串合併成一個字符串。
#include <iostream> #include <cstring> using namespace std; int main() { char str1[20] = "Hello"; char str2[] = "World"; strcat(str1, str2); //將str2合併到str1中 cout << str1 << endl; //輸出HelloWorld return 0; }
上述代碼中,我們使用了函數strcat將str2拼接到了str1中。
三、字符串比較
字符串比較常用於比較兩個字符串的大小關係,判斷它們是否相等。
#include <iostream> #include <cstring> using namespace std; int main() { char str1[] = "Hello"; char str2[] = "World"; int cmp = strcmp(str1, str2); if(cmp < 0) { cout << str1 << " is less than " << str2 << endl; } else if(cmp > 0) { cout << str1 << " is greater than " << str2 << endl; } else { cout << str1 << " is equal to " << str2 << endl; } return 0; }
上述代碼中,我們使用了函數strcmp比較了兩個字符串的大小關係。當cmp小於0時,說明str1小於str2;當cmp大於0時,說明str1大於str2;當cmp等於0時,說明str1等於str2。
四、字符串查找
字符串查找常用於查找一個子串在一個字符串中出現的位置。
#include <iostream> #include <cstring> using namespace std; int main() { char str[] = "Hello World"; char sub[] = "Wo"; char *pos = strstr(str, sub); if(pos != NULL) { cout << "Substring found at position " << pos-str << endl; } else { cout << "Substring not found" << endl; } return 0; }
上述代碼中,我們使用了函數strstr查找子串sub在字符串str中出現的位置。
五、自定義字符串操作
除了上述常見的字符串操作外,我們還可以自定義字符串操作。
#include <iostream> #include <cstring> using namespace std; void reverseString(char *str) { int len = strlen(str); for(int i=0; i<len/2; i++) { char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; } } int main() { char str[] = "Hello World"; reverseString(str); cout << str << endl; //輸出dlroW olleH return 0; }
上述代碼中,我們自定義了一個字符串操作reverseString,用於將一個字符串反轉。
總結
字符串操作在編程中非常常見、必要,掌握字符串操作可以幫助我們更好地編寫C++程序。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/154029.html