user1340113
user1340113

Reputation: 41

Iteration, find

Please help! How would i find and remove leading underscores by iterating through looking at the characters and counting the number of underscores before a valid character occurs. As well as iterating backwards from the end of the string to find any trailing underscores.

I can use the following method, to erase the underscore, but how would is iterate to find underscores.

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

If user enters a string of ___twenty_three__, the end result should be twenty_three. So only the leading and trailing underscore are deleted.

Upvotes: 4

Views: 183

Answers (3)

keety
keety

Reputation: 17441

Something on these lines

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));
}

Upvotes: 1

Iceman
Iceman

Reputation: 4362

Pseudocode for leading characters:

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

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

For trailing characters:

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

Upvotes: 0

David D
David D

Reputation: 1591

Something like this should use the string library's find_first_not_of and find_last_not_of. There are great code examples on those pages.

// 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;
}

Upvotes: 2

Related Questions