首页 > 解决方案 > 替换字符串 C++ 位置 X 中的单词

问题描述

我正在尝试在程序中编写一个函数,该函数将接受一个字符串、一个单词和一个整数,并将 int 作为索引值,将单词作为替换值。例如,如果字符串是“This is a test.”,单词是“example”,数字是 4,那么结果将是“This is an example”。这就是我到目前为止所拥有的(我必须制作字符串的多个副本,因为最终,我将通过引用而不是作为值将它传递给其他两个函数)现在它使用字符索引而不是单词索引以替换。我该如何解决?

#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;
 }

标签: c++stringfunction

解决方案


您要做的第一件事是找到第 n 个单词。

首先想到的是用astd::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();

虽然这很容易编写,但它有两个问题: 它在stringAND 中丢失了正确类型的空格,在字符串的末尾放置了一个额外的空格。与在适当位置修改字符串相比,它也有点慢并且使用更多的内存。

用于std::string::find_first_not_of查找第一个非空白字符。这将是第一个单词的开始。然后用于std::string::find_first_of查找下一个空白字符。这将是这个词的结尾。交替来回查找非空格,然后查找空格,直到找到第 n 个单词的开头和结尾。std::string::replace那个词。这种方法需要您编写越来越复杂的代码,但更令人满意。这就是我概述它而不是完全实施它的原因:让你自己享受快乐。

注意:void stringFunctionValue(string StringCopy1, int Number, string Word)使您无法将结果提供给用户。这导致了无用的功能。考虑返回 astring而不是void.


推荐阅读