c++ - 用增加的数字替换字符串中的空格
问题描述
我需要一个程序来获取一个字符串并用越来越多的数字替换空格。
#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
解决方案
为了方便和清晰,改变你的方法。
- 将字符串放入
istringstream
- 提取每个空格分隔的子字符串并放入
std::vector<string>
- 将向量的内容送入 a
stringstream
和 - 用于
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++);
}
推荐阅读
- .net - 流的意外结束,在我朋友的电脑上,但不是我的。.Net 核心,SQL
- spring-security - Spring 安全性:ldap 配置
- android - 确定 Google 帐户是否可用
- django - 在进行连接的 Django 过滤器查询方法中使用 TO_CHAR
- java - Jackson:InvalidFormatException:无法从字符串值构造 java.util.Date 的实例
- c++ - 为什么给定默认值时,此模板参数推导失败?
- liquibase - 配置 SQL 输出
- google-bigquery - 从地理点 BigQuery 创建多边形
- java - 如何创建一个可以模拟 Ctrl + F(查找)功能的 Intellij 插件。
- .net-core - aspnet 核心 appsettings.json 加载