[英]Function to find and replace string in char array (streams) c++
我正在嘗試找到一種方法來查找在char數組中搜索字符串的方法,然后在每次發生時將其替換為另一個字符串。 我對如何做有一個很好的想法,但流后面的整個語法有時會讓我感到困惑。 無論如何我的代碼到目前為止(並且它不是很多)是:
string FindWord = "the";
string ReplaceWord = "can";
int i = 0;
int SizeWord = FindWord.length();
int SizeReplace = ReplaceWord.length();
while ( Memory[i] != '\0')
{
//now i know I can probably use a for loop and
//then if and else statements but im just not quite sure
i++; //and then increment my position
}
我通常不會這么慢:/任何想法?
在將其轉換為std::string
之后,我更喜歡使用字符數組
以下是很容易遵循: -
#include<iostream>
#include<string>
int main ()
{
char memory[ ] = "This is the char array";
//{'O','r',' ','m','a','y',' ','b','e',' ','t','h','i','s','\0'};
std::string s(memory);
std::string FindWord = "the";
std::string ReplaceWord = "can";
std::size_t index;
while ((index = s.find(FindWord)) != std::string::npos)
s.replace(index, FindWord.length(), ReplaceWord);
std::cout<<s;
return 0;
}
你需要兩個 for循環,一個在另一個里面。 外部for循環一次通過Memory
字符串一個字符。 內部循環開始在外部循環中查找您所在位置的FindWord
。
這是一個經典案例,您需要將問題分解為更小的步驟。 您正在嘗試的可能有點過於復雜,無法一次性完成。
請嘗試以下策略
1)編寫一些代碼來查找另一個字符串中給定位置的字符串,這將是內部循環。
2)將步驟1中的代碼放在另一個循環(外循環)中,該循環遍歷您正在搜索的字符串中的每個位置。
3)現在您可以在另一個字符串中找到所有出現的字符串,添加替換邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.