迭代,找到

时间:2012-04-19 00:55:17

标签: c++ string iterator iteration

请帮忙!如何在有效字符出现之前通过查看字符并计算下划线的数量来查找和删除前导下划线。以及从字符串末尾向后迭代以查找任何尾随下划线。

我可以使用以下方法来擦除下划线,但是如何迭代来查找下划线。

resultF.erase(resultF.length()- trailingCount);
resultF.erase(0,leadingCount);

如果用户输入 ___ twenty_three __ 字符串,则最终结果应为twenty_three。因此只删除前导和尾随下划线。

3 个答案:

答案 0 :(得分:2)

这样的事情应该使用字符串库的find_first_not_offind_last_not_of。这些页面上有很多代码示例。

// From the links above: 
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("erase trailing white-spaces   \n");
  string whitespaces (" \t\f\v\n\r");
  size_t found;

  found=str.find_last_not_of(whitespaces);
  if (found!=string::npos)
    str.erase(found+1);
  else
    str.clear();            // str is all whitespace

  cout << '"' << str << '"' << endl;

  return 0;
}

答案 1 :(得分:1)

这些方面的东西

string remove_(const string& str) {
  int i,j;
  int n = str.length();
  for(i=0;i < n && (str[i] != '_');i++);
  for(j=n;j > 0 && (str[j-1] != '_');j--);
   if(j <= i)
      return string(); //all underscores
  return ((str).substr(i,j-i));
}

答案 2 :(得分:0)

前导字符的伪代码:

std::string *str;
int ct = 0;

while(*str != '_'){
str++;
ct++;
}

For trailing characters:

while (* (str+length) != '_') {
str--;
ct++;
}