C++中的string类型是一种字符串类型,它可以用来操作字符串。它提供了许多有用的函数,可以用来查找、替换、插入和删除字符串中的字符,以及比较两个字符串的大小等。
1. 创建字符串
可以使用string类的构造函数来创建字符串,例如:
string str1; // 创建空字符串 string str2 = "Hello World!"; // 使用字符串字面量创建字符串 string str3 = str2; // 使用已存在的字符串创建新的字符串 string str4(str3); // 使用拷贝构造函数创建新的字符串
2. 字符串比较
可以使用string类的compare函数来比较两个字符串的大小,例如:
string str1 = "Hello"; string str2 = "World"; if (str1.compare(str2) == 0) { cout << "str1 and str2 are equal" << endl; } else if (str1.compare(str2) < 0) { cout << "str1 is less than str2" << endl; } else { cout << "str1 is greater than str2" << endl; }
3. 查找字符串
可以使用string类的find函数来查找字符串中的字符,例如:
string str = "Hello World"; // 查找字符 'o' 的位置 size_t pos = str.find('o'); if (pos != string::npos) { cout << "Found 'o' at position " << pos << endl; } else { cout << "Character 'o' not found" << endl; } // 查找字符串 "World" 的位置 pos = str.find("World"); if (pos != string::npos) { cout << "Found \"World\" at position " << pos << endl; } else { cout << "String \"World\" not found" << endl; }
4. 替换字符串
可以使用string类的replace函数来替换字符串中的字符,例如:
string str = "Hello World"; // 替换字符 'o' 为 'a' str.replace(str.find('o'), 1, "a"); // 替换字符串 "World" 为 "Universe" str.replace(str.find("World"), 5, "Universe"); cout << str << endl; // 输出 "Hell a Universe"
5. 插入字符串
可以使用string类的insert函数来插入字符串,例如:
string str = "Hello"; // 在字符串末尾插入字符 '!' str.insert(str.length(), "!"); // 在字符串的第 5 个位置插入字符 ',' str.insert(4, ","); cout << str << endl; // 输出 "Hell,o!"
6. 删除字符串
可以使用string类的erase函数来删除字符串,例如:
string str = "Hello World"; // 删除字符串的一个字符 str.erase(str.length() - 1); // 删除字符串的第 5 个字符 str.erase(4, 1); cout << str << endl; // 输出 "Hell World"
以上是,通过使用这些函数,可以方便地操作字符串。