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

问题描述 投票:2回答:1

问题是我不知道输入字符串的长度。如果输入字符串为“ 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
c++ c++14 str-replace
1个回答
5
投票

使用正则表达式。

示例:

#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'的大小写混合形式。该正则表达式的示例输出:

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::regex yy_re("yy"); // 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, yy_re, "%y");
        } else {
            output = std::regex_replace(text, y_re, "%Y");
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.