c++ - 替换字符串 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;
}
解决方案
您要做的第一件事是找到第 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();
虽然这很容易编写,但它有两个问题: 它在string
AND 中丢失了正确类型的空格,在字符串的末尾放置了一个额外的空格。与在适当位置修改字符串相比,它也有点慢并且使用更多的内存。
用于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
.
推荐阅读
- javascript - 添加到 Promise 的成功和拒绝处理程序不会激活
- python - 我怎样才能提高这种图像的 tesseract 的准确性?
- javascript - 如何使用 MVC 在 IIS 中发布后修复 DataTables 不起作用
- bash - 使用 bash for 循环遍历文件
- mysql - MYSQL从文本文件输入加载空值
- php - 如果 1.1.2.254 存在于我的数据库中!使用下一个 1.1.2.253 问题
- azure - MLFlow 模型注册表 ENDPOINT_NOT_FOUND:未找到错误的 API
- android - 房间数据库关闭后如何重新打开
- javascript - 在 vue-app 中将代码从一个组件转移到另一个组件?
- swift - 组合片段在功能中不起作用,我该如何让它工作