使用C++将一个字符串替换为另一个字符串

Replace a string to another string using C++

本文关键字:字符串 一个 替换 另一个 C++ 使用      更新时间:2023-10-16

问题是我不知道输入字符串的长度。只有当输入字符串为"yyyy"时,我的函数才能替换。我认为解决方案是,首先,我们将尝试将输入字符串转换回"yyyy",并使用我的函数来完成这项工作。

这是我的功能:

void findAndReplaceAll(std::string & data, std::string toSearch, std::string replaceStr)
{
// Get the first occurrence
size_t pos = data.find(toSearch);
// Repeat till end is reached
while( pos != std::string::npos)
{
// Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
// Get the next occurrence from the current position
pos = data.find(toSearch, pos + replaceStr.size());
}
}

我的主要功能

std::string format = "yyyyyyyyyydddd";
findAndReplaceAll(format, "yyyy", "%Y");
findAndReplaceAll(format, "dd", "%d");

我的预期输出应该是:

%Y%d

使用正则表达式。

示例:

#include <iostream>
#include <string>
#include <regex>
int main(){
std::string text = "yyyyyy";
std::string sentence = "This is a yyyyyyyyyyyy.";
std::cout << "Text: " << text << std::endl;
std::cout << "Sentence: " << sentence << std::endl;
// Regex
std::regex y_re("y+"); // this is the regex that matches y yyy or more yyyy
// replacing
std::string r1 = std::regex_replace(text, y_re, "%y"); // using lowercase
std::string r2 = std::regex_replace(sentence, y_re, "%Y"); // using upercase 
// showing result
std::cout << "Text replace: " <<   r1 << std::endl;
std::cout <<  "Sentence replace: " << r2 << std::endl;
return 0;
}

输出:

Text: yyyyyy
Sentence: This is a yyyyyyyyyyyy.
Text replace: %y
Sentence replace: This is a %Y.

如果你想让它变得更好,你可以使用:

// Regex
std::regex y_re("[yY]+");

对于任意数量的"Y",它将匹配小写和大写的任何组合。Regex:的示例输出

Sentence: This is a yYyyyYYYYyyy.
Sentence replace: This is a %Y.

这只是你可以用regex做什么的一个简单例子,我建议你看看这个主题本身,在SO和其他网站上有很多信息。

额外:如果你想在替换之前进行匹配以替换,你可以做一些类似的事情:

// Regex
std::string text = "yyaaaa";
std::cout << "Text: " << text << std::endl;
std::regex y_re("y+"); // this is the regex that matches y yyy or more yyyy

std::string output = "";
std::smatch ymatches;
if (std::regex_search(text, ymatches, y_re)) {
if (ymatches[0].length() == 2 ) {
output = std::regex_replace(text, y_re, "%y");
} else {
output = std::regex_replace(text, y_re, "%Y");
}
}
相关文章: