如何指向 std::string 中固定位置的分隔符

how to point to delimiter at fixed position in std::string

说我有文本说用“#”作为分隔符。 示例

 std::string key = "012#txt1#txt2#txt3#txt4#  #some other text:"

我必须在 #at 位置 5 和 #at 位置 6 之间插入修改后的文本。如上所示,中间有空格。

为此,我需要找到第 5 个# 和第 6 个#。 我写了一个小代码,但它没有按照我的预期 do.It 总是 return 首先找到“#”。有人可以给我建议吗。

std::string temp = key;
 size_t found = 0;

  size_t pos_key = temp.find('#');
  while( ( found !=5 )&& ( pos_key != std::string::npos )  )
    {
        found++;
        temp.find_first_of('#', pos_key + 1 );
        temp.erase(0, pos_key );
    }
  std::cout << " the pos key is " << pos_key << std::endl ;

有几个问题正在发生。首先你永远不会更新 pos_key 所以当你调用 erase 时你会踩到你的字符串,我不确定你为什么要这样做。如果您需要找到第 n 个符号,您可以使用如下函数:

size_t find_nth(const std::string & line, const std::string & symbol, size_t nth)
{
    size_t pos = 0;
    size_t counter = 0;
    while (counter < nth && (pos = line.find(symbol, pos)) != std::string::npos)
    {
        counter++; // found a match so increment
        pos++;  // increment so we search for the next one
    }
    return pos;
} 

你可以在这个Live Example

中看到它运行

看来你有两个问题。

首先你找到它时不记得'#'的位置,你需要将std::string::find_first_of函数的return值赋给pos_key

其次你继续删除字符串的内容直到你找到的位置。这会丢弃您从 std::string::find_first_of 函数获得的所有位置信息。

我认为这可能是您需要的:

int main()
{
    std::string key = "012#txt1#txt2#txt3#txt4#  #some other text:";

    std::string temp = key;
    size_t found = 0;

    size_t pos_key = temp.find('#');
    while((found != 5) && (pos_key != std::string::npos))
    {
        found++;
        // this line does nothing with the found position
        // temp.find_first_of('#', pos_key + 1);

        // instead record the position of the latest '#'
        pos_key = temp.find_first_of('#', pos_key + 1);

        // this line just deletes most of the string
        // for no apparent reason
        // temp.erase(0, pos_key);
    }
    std::cout << " the pos key is " << pos_key << std::endl;
}