首页 > 解决方案 > 用增加的数字替换字符串中的空格

问题描述

我需要一个程序来获取一个字符串并用越来越多的数字替换空格。

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

int main()
{

    // Get the String
    string str = "this essay needs each word to be numbered";
    int num = 1;
    string x = num;
    int i = 0;



    // read string character by character.
    for (i < str.length(); ++i) {

        // Changing the loaded character
        // to a number if it's a space.
        if (str[i] == ' ') {

            str[i] = x;
            ++num

        }
    }

    // testing outputs
    cout << str << endl;
    cout << num << endl;

  ofstream file;
  file.open ("numbered.txt");
  file << str;
  file.close();

    return 0;
}

我有它可以用字母或符号替换空格并保存到新文件,但是当我尝试将其设为数字​​时它停止工作。我需要它说“this1essay2needs3each4word5to6be7numbered

标签: c++

解决方案


为了方便和清晰,改变你的方法。

  • 将字符串放入istringstream
  • 提取每个空格分隔的子字符串并放入std::vector<string>
  • 将向量的内容送入 astringstream
  • 用于std::to_string(num)在子字符串之间添加数字

例如:

    std::string str = "this essay needs each word to be numbered";
    int num = 1;

    std::istringstream istr(str);
    std::string temp;
    std::vector<std::string> substrs;
    while (istr >> temp)
    {
      substrs.push_back(temp);
    }
    std::stringstream ostr;
    for (auto&& substr : substrs)
    {
      ostr << substr << std::to_string(num++);
    }

推荐阅读