使用另一个字符串从字符串中删除空格

Removing spaces from String using another string

本文关键字:字符串 删除 空格 另一个      更新时间:2023-10-16

我正在尝试从字符串中删除空格,尝试使用字符串本身,但它根本不起作用。在调试时,我发现它在字符串 str1 中输入了奇怪的值,我不明白它为什么这样做。以下是附加的代码,可能有什么问题?为什么它不起作用?

string str = "Hello World";
string str1 = " ";
int increment = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
continue;
}
else {
str1[increment] += str[i];
increment++;
}
}

str1[increment]对于任何increment > 0都是UB,因为str1的长度只有1。您还将字符的值添加到每个元素,而不是附加字符串。只需更改

str1[increment] += str[i]

str1 += str[i]

并将string str1 = " ";更改为string str1;

与其编写循环,不如使用 STL 算法函数进行擦除。

首先,如果给定适当的参数,算法函数不会失败。

其次,代码本身基本上是自我记录的。

例如,如果有人看你的手工编码循环,乍一看你试图完成什么并不明显。 另一方面,当C++程序员看到std::remove时,它会立即知道它会做什么。

将使用的 STL alogrithm 函数是 std::remove,以及使用 std::string::erase((:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string str = "Hello World";
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
std::cout << str;
}

输出:

HelloWorld

它是python中的代码:

txt = "hello world" spaces = " "
txt = txt.replace(" ", "")

print(txt)

您可以将其更改为所需的任何语言。 它删除句子中的空格。

首先,在这里增加值。未分配:

str1[increment] += str[i];

我想你想做:

str1[increment] = str[i];

由于您将 str1 声明为 " ",因此您将获得一个小缓冲区,因此在这种情况下,您无法在 str[n] 上为 n> 0 分配某些内容。正确的方法是:

string str = "Hello World";
string str1;
for (int i = 0; i < str.length(); i++)
if (str[i] != ' ')
str1 += str[i];

或者,如果你真的需要按照你正在做的事情去做,我建议使用 char* 而不是 std::string

string str = "Hello World";
char str1[str.length()];
int increment = 0;
for (int i = 0; i < str.length(); i++)
if (str[i] != ' ')
str1[increment++] = str[i];

str1[increment] = '';

最后,变量increment将是str1的确切大小。您可以在末尾转换为字符串:

string s = str1;