在C++中,可以使用以下方法删除字符串中的空格:

  1. 使用迭代器遍历字符串,判断每个字符是否为空格,如果是则删除:
string removeSpaces(string str) {
    str.erase(remove(str.begin(), str.end(), ' '), str.end());
    return str;
}
  1. 使用循环遍历字符串,判断每个字符是否为空格,如果是则删除:
string removeSpaces(string str) {
    string result = "";
    for (int i = 0; i < str.length(); i++) {
        if (str[i] != ' ') {
            result += str[i];
        }
    }
    return result;
}
  1. 使用stringstream将字符串分割成单词,然后再重新拼接:
string removeSpaces(string str) {
    stringstream ss(str);
    string word, result = "";
    while (ss >> word) {
        result += word;
    }
    return result;
}

以上方法都会返回删除了空格的字符串

字符串删除空格c++

原文地址: https://www.cveoy.top/t/topic/hYLr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录