4

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

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

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

如果用户输入字符串___twenty_three__,最终结果应该是 20_3。所以只有前导和尾随下划线被删除。

4

3 回答 3

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;
}
于 2012-04-19T01:05:06.493 回答
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));
}
于 2012-04-19T01:11:07.350 回答
0

前导字符的伪代码:

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

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

For trailing characters:

while (* (str+length) != '_') {
str--;
ct++;
}
于 2012-04-19T01:05:13.957 回答