c++string替换空格为空
时间: 2023-08-18 20:05:45 浏览: 235
你可以使用C++的string类的replace函数来替换字符串中的空格为空。下面是一个示例代码:
```cpp#include <iostream>
#include <string>
int main() {
std::string str = "Hello World! This is a test.";
// 替换空格为空 size_t pos = str.find(" ");
while (pos != std::string::npos) {
str.replace(pos,1, "");
pos = str.find(" ");
}
std::cout << str << std::endl;
return0;
}
```
这段代码会将字符串中的所有空格替换为空字符串。输出结果为:"HelloWorld!Thisisatest."
相关问题
C++string替换符号
在 C++ 中,可以使用 string 类的 replace() 函数来替换字符串中的符号。replace() 函数的语法如下:
```c++
string& replace (size_t pos, size_t len, const string& str);
```
其中,pos 表示要替换的子字符串的起始位置,len 表示要替换的子字符串的长度,str 表示用来替换子字符串的字符串。
例如,如果要将字符串中的所有逗号替换成空格,可以使用如下代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, World!";
size_t pos = 0;
while ((pos = str.find(',', pos)) != string::npos)
{
str.replace(pos, 1, " ");
pos++;
}
cout << str << endl;
return 0;
}
```
输出结果为:
```
Hello World!
```
devc++代码替换空格
在DevC++中,可以使用字符串的替换函数`replace`来替换空格。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World! This is a test.";
// 替换空格为指定字符
char replaceChar = '-';
size_t found = str.find(' ');
while (found != string::npos) {
str.replace(found, 1, 1, replaceChar);
found = str.find(' ', found + 1);
}
cout << "替换后的字符串:" << str << endl;
return 0;
}
```
上述代码中,我们首先定义了一个字符串`str`,然后使用`find`函数找到第一个空格的位置,然后使用`replace`函数将该位置的空格替换为指定字符。接着,使用循环继续查找并替换剩余的空格,直到没有空格为止。最后,输出替换后的字符串。