C++字符串中’- ‘替换为’-‘
时间: 2023-09-24 15:09:21 浏览: 78
你可以使用C++中的replace函数来替换字符串中的字符。具体步骤如下:
1. 定义一个字符串变量str并初始化。
2. 使用replace函数将字符串中的字符'-'替换为'-'。
3. 输出替换后的字符串。
示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "C++字符串中'- '替换为'-'";
replace(str.begin(), str.end(), '-', '-');
cout << str << endl;
return 0;
}
```
输出结果为:
```
C++字符串中'- '替换为'-'
```
相关问题
C++字符串的使用-string类
在 C++ 中,我们通常使用字符串来存储和操作文本数据。C++ 中有多种字符串类型,其中最常用的是 string 类。这个类定义在头文件 <string> 中,使用时需要包含该头文件。
下面是一些 string 类的基本用法:
1. 定义字符串变量:
```
string str = "Hello World";
```
2. 字符串拼接:
```
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2; // str3 = "Hello World"
```
3. 字符串长度:
```
string str = "Hello World";
int len = str.length(); // len = 11
```
4. 字符串查找:
```
string str = "Hello World";
int index = str.find("World"); // index = 6
```
5. 字符串替换:
```
string str = "Hello World";
str.replace(6, 5, "C++"); // str = "Hello C++"
```
6. 字符串截取:
```
string str = "Hello World";
string subStr = str.substr(6, 5); // subStr = "World"
```
7. 字符串转整数:
```
string str = "123";
int num = stoi(str); // num = 123
```
8. 整数转字符串:
```
int num = 123;
string str = to_string(num); // str = "123"
```
除了上面这些基本用法,string 类还提供了很多其他的成员函数,可以根据需要进行使用。
c++ 替换字符串中的空格为_
你可以使用C++的string类和replace函数来替换字符串中的空格为下划线。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World! This is a test.";
std::string search = " ";
std::string replace = "_";
size_t pos = 0;
while ((pos = str.find(search, pos)) != std::string::npos) {
str.replace(pos, search.length(), replace);
pos += replace.length();
}
std::cout << str << std::endl;
return 0;
}
```
这段代码中,我们首先定义了一个字符串`str`,然后定义了要搜索的字符串`search`和要替换的字符串`replace`。接着使用`std::string`的`find`函数来查找字符串中的空格位置,并使用`replace`函数进行替换。通过循环,我们可以替换所有的空格。
运行这段代码后,输出将会是`Hello_World!_This_is_a_test.`,所有的空格都被替换为了下划线。