You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C++的cstring库移除字符时遇多余空格问题求助

如何移除字符串中的'-'而不产生额外空格?

你的问题出在代码逻辑上:你把'-'替换成了空格,而输入里"had"后面本来就有一个空格,加上替换后的空格,就变成了两个连续空格。要得到期望的输出,咱们需要直接删除'-'字符,而不是替换成空格。这里有几种可行的解决方法:

方法1:用C风格字符串的双指针法

这种方法适配你当前使用的char数组,通过两个指针构建新字符串,跳过所有'-':

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char a[101];
    cin.getline(a, 101);
    int j = 0; // j用来记录新字符串的位置
    for (int i = 0; a[i] != '\0'; i++) {
        // 只保留非'-'的字符
        if (a[i] != '-') {
            a[j++] = a[i];
        }
    }
    a[j] = '\0'; // 必须添加字符串结束符,否则会输出垃圾内容
    cout << a << endl;
}

当你输入i had -34 ms时,这段代码会直接跳过'-',把后面的'3'移到原来'-'的位置,最终输出i had 34 ms,完美符合你的期望。

方法2:使用C++ string类(更简洁)

如果可以改用C++的string类型,代码会更易读和维护,这里有两种写法:

写法1:遍历构建新字符串

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    string result;
    for (char c : s) {
        if (c != '-') {
            result += c;
        }
    }
    cout << result << endl;
}

写法2:用algorithm库的remove+erase组合(高效简洁)

这是C++中删除特定字符的经典写法,利用标准库算法完成:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    // remove把所有'-'移到字符串末尾,erase删除这些多余的部分
    s.erase(remove(s.begin(), s.end(), '-'), s.end());
    cout << s << endl;
}

这两种写法都能直接删除所有'-'字符,不会产生额外的空格,完全满足你的需求。

内容的提问来源于stack exchange,提问作者Bunta Ervin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:02:47