C++中数组与字符串的深入解析
立即解锁
发布时间: 2025-08-19 01:36:31 阅读量: 3 订阅数: 6 


C++面向对象编程入门与实践
### C++ 中数组与字符串的深入解析
#### 1. 字符串操作函数
在 C++ 里,字符串操作是常见的编程任务。下面是一些常用的字符串操作函数及其示例代码:
```cpp
s1.erase(0, 7); //remove “Quick! “
s1.replace(9, 5, s2); //replace “Count” with “Lord”
s1.replace(0, 1, “s”); //replace ‘S’ with ‘s’
s1.insert(0, s3); //insert “Don’t “ at beginning
s1.erase(s1.size()-1, 1); //remove ‘.’
s1.append(3, ‘!’); //append “!!!”
int x = s1.find(‘ ‘); //find a space
while( x < s1.size() ) //loop while spaces remain
{
s1.replace(x, 1, “/”); //replace with slash
x = s1.find(‘ ‘); //find next space
}
cout << “s1: “ << s1 << endl;
```
这些函数的具体作用如下:
- `erase()`:从字符串中移除子字符串。第一个参数是子字符串首字符的位置,第二个参数是子字符串的长度。例如,`s1.erase(0, 7)` 移除了字符串开头的 “Quick! ”。
- `replace()`:用另一个字符串替换原字符串的一部分。第一个参数是替换开始的位置,第二个参数是原字符串中要替换的字符数,第三个参数是替换字符串。如 `s1.replace(9, 5, s2)` 将 “Count” 替换为 “Lord”。
- `insert()`:在指定位置插入字符串。例如,`s1.insert(0, s3)` 在 `s1` 开头插入 “Don’t ”。
- `append()`:在字符串末尾添加字符。`s1.append(3, ‘!’)` 在字符串末尾添加了三个感叹号。
- `find()`:查找子字符串或字符的位置。在上述代码中,使用 `find()` 查找空格,并将其替换为斜杠。
下面是操作流程的 mermaid 流程图:
```mermaid
graph TD;
A[开始] --> B[移除 “Quick! ”];
B --> C[替换 “Count” 为 “Lord”];
C --> D[替换 ‘S’ 为 ‘s’];
D --> E[在开头插入 “Don’t ”];
E --> F[移除末尾的 ‘.’];
F --> G[添加三个感叹号];
G --> H[查找空格];
H --> I{是否找到空格};
I -- 是 --> J[替换空格为斜杠];
J --> H;
I -- 否 --> K[输出结果];
K --> L[结束];
```
#### 2. 字符串对象的比较
可以使用重载运算符或 `compare()` 函数来比较字符串对象,以此判断字符串是否相同,或者它们在字母顺序上的先后关系。以下是示例代码:
```cpp
//sstrcom.cpp
//comparing string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
string aName = “George”;
string userName;
cout << “Enter your first name: “;
cin >> userName;
if(userName==aName) //operator ==
cout << “Greetings, George\n”;
else if(userName < aName) //operator <
cout << “You come before George\n”;
else
cout << “You come after George\n”;
//compare() function
int n = userName.compare(0, 2, aName, 0, 2);
cout << “The first two letters of your name “;
if(n==0)
cout << “match “;
else if(n < 0)
cout << “come before “;
else
cout << “come after “;
cout << aName.substr(0, 2) << endl;
return 0;
}
```
在这个程序中:
- 第一部分使用 `==` 和 `<` 运算符判断用户输入的名字与 “George” 是否相等,或者在字母顺序上的先后关系。
- 第二部分使用 `compare()` 函数比较用户输入名字和 “George” 的前两个字母。
以下是比较流程的表格:
| 比较方式 | 示例代码 | 作用 |
| ---- | ---- | ---- |
| 重载运算符 `==` | `if(userName==aName)` | 判断两个字符串是否相等 |
| 重载运算符 `<` | `else if(userName < aName)` | 判断一个字符串是否在字母顺序上先于另一个字符串 |
| `compare()` 函数 | `int n = userName.compare(0, 2, aName, 0, 2)` | 比较指定位置和长度的子字符串 |
#### 3. 访问字符串对象中的字符
访问字符串对象中的单个字符有多种方式,下面是使用 `at()` 成员函数的示例代码:
```cpp
//sstrchar.cpp
//accessing characters in string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
char charray[80];
string word;
cout << “Enter a word: “;
cin >> word;
int wlen = word.length();
```
0
0
复制全文
相关推荐










