替换字符串位置 X 中的单词C++

Replacing word in position X of a string C++

本文关键字:单词 C++ 字符串 位置 替换      更新时间:2023-10-16

我正在尝试在程序中编写一个函数,该函数将接受字符串,单词和整数,并使用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