c++ - 字符串 find_first 不更新字符串

标签 c++ string replace find

嘿,我有一个小问题,这个程序按预期工作

它需要一个字符串测试,替换所有的“!”对于“.”,标识是“?”和“。” are ,然后它把 does 值放在一个 vector 上,它只打印字符串中有问题的部分,如果字符串没有任何“!”,它就可以正常工作。但是如果它有它就不能再识别所有的问题了。

如果字符串是这样的就可以了

std::string test ("ver. what? lol. o que e isto? nao sei. ola? haha. why? adeus. oi! an? haha. lool! ");

但是如果是这样的话,是找不到问题的。

std::string test ("ver! what? lol! o que e isto? nao sei! ola? haha. why? adeus. oi! an? haha. lool! ");

但是颂歌的这一部分应该取代所有的“!”用 "."这样代码就可以工作了

while (found!=std::string::npos)
{
  //std::cout << found << '\n';
  test[found]='.';
  found=test.find_first_of("!",found+1);
  std::cout << test << '\n';
}

感谢帮助

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <cstddef>

using namespace std;

int main ()
{
    std::vector< int > interrogation ;
    std::vector< int > dot;

    string look = "?";
    string look_again = ".";
    std::string test ("ver! what? lol! o que e isto? nao sei! ola? haha. why? adeus. oi! an? haha. lool! ");
    std::size_t found = test.find_first_of("!");

    string::size_type pos = test.find(look);
    string::size_type sop = test.find(look_again);

    while (found!=std::string::npos)
    {
        //std::cout << found << '\n';
        test[found]='.';
        found=test.find_first_of("!",found+1);
        std::cout << test << '\n';
    }

    std::cout << test << '\n';

    while (pos != std::string::npos)
    {

        int a = pos ;

        //cout << " . found at : " << sop << std::endl;

        interrogation.push_back(a);

        string fragment = test.substr (0 , pos  );    // works
        //cout << fragment << endl ;

        pos = test.find(look, pos + 1);
    }

    while (sop != std::string::npos)
    {

        int b = sop;

        //cout << " ? found at : " << pos << std::endl;

        dot.push_back(b);

        string fragment2 = test.substr (0 , sop) ;    // works
        //cout << fragment2 << endl ;

        sop = test.find(look_again, sop + 1);
    }

    while( interrogation.size() > 0){

        std::cout << test << '\n';

        while(dot.back() > interrogation.back())
        {
            cout << "dot.pop_back" << endl;
            dot.pop_back();
        }

        string fragment = test.substr (dot.back() + 1,  interrogation.back() -     dot.back());
        cout << "question with dot \n" << fragment << endl ;

        interrogation.pop_back() ;
    }
}

最佳答案

在替换 之前,您正在寻找第一个 . 位置(-> string::size_type sop = test.find(look_again);)!. (-> while (found!=std::string::npos) { ... })。在将 ! 替换为 .while 循环之后对 sop 进行赋值。

关于c++ - 字符串 find_first 不更新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858161/

相关文章:

javascript - 动态正则表达式组操作

c++ - 可变参数

c# - 将逗号分隔的字符串解析为某种我可以循环访问各个值的对象的最简单方法?

java - 检查字符串是否代表Java中的整数的最佳方法是什么?

python - 左括号的位置

javascript - 在 javascript 中,replace() 方法正在替换其中包含实际替换部分的单词

JavaScript,RegExp - 替换为涉及标记表达式的评估表达式?

c++ - 来自视频文件的简单帧抓取器

c++ - 如何正确格式化类实例引用

c++ - 当类包含指向另一个对象的指针时重载赋值运算符