替换字符串位置 X 中的单词C++
Replacing word in position X of a string C++
我正在尝试在程序中编写一个函数,该函数将接受字符串,单词和整数,并使用int作为索引值,单词作为替换值。例如,如果字符串是"这是一个测试",单词是"example",数字是 4,那么结果将是"这是一个示例"。这就是我到目前为止所拥有的(我不得不制作字符串的多个副本,因为最终,我将通过引用而不是作为值将其传递到另外两个函数中(现在它正在使用字符索引而不是单词索引来替换。我该如何解决这个问题?
#include "pch.h"
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string Input = "";
string Word = "";
int Number = 0;
cout << "Pleas enter a string using only lower case letters. n";
getline(cin, Input);
cout << "Please enter a word using only lower case lettersS. n";
getline(cin, Word);
cout << "Please enter a number. n";
cin >> Number;
string StringCopy1 = Input;
string StringCopy2 = Input;
string StringCopy3 = Input;
}
void stringFunctionValue(string StringCopy1, int Number, string Word)
{
StringCopy1.replace(Number, Word.length, Word);
return StringCopy1;
}
你要做的第一件事是找到第n个单词。
首先要想到的是使用std::istringstream
将字符串拉开,并>>
和std::ostringstream
来写入新字符串。
std::istringstream in(StringCopy1);
std::string token;
std::ostringstream out;
int count = 0;
while (in >> token) // while we can get more tokens
{
if (++count != number) // not the number of the token to replace
{
out << token << " "; // write the token
}
else
{
out << word << " "; // write the replacement word
}
}
return out.str();
虽然这很容易编写,但它有两个问题:它在string
中丢失了正确类型的空格,并在字符串的末尾放置了一个额外的空格。它也有点慢,并且比您就地修改字符串使用更多的内存。
使用std::string::find_first_not_of
查找第一个非空格字符。这将是第一个词的开始。然后使用std::string::find_first_of
查找下一个空格字符。这将是这个词的结尾。来回交替查找非空格,然后找到空格,直到找到第 n 个单词的开头和结尾。std::string::replace
这个词。这种方法需要您编写越来越复杂的代码,但更令人满意。这就是为什么我概述了它而不是完全实施它:让你自己快乐。
注意:void stringFunctionValue(string StringCopy1, int Number, string Word)
无法将结果反馈给用户。这会导致函数无用。考虑返回string
而不是void
。
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 当您在此单词中搜索单词时调整字符数组的大小?
- 数每个单词的元音
- 我们如何在文本文件中找到C++中的几个单词?
- 使用 BFS 的单词梯 2
- 替换字符串中的单词,但忽略引号中的单词