1

In JavaScript if we have a string with a separator, we can remove leading items in this way:

console.log(('/dev/input/event11').split('/').slice(2).join('/'))

output: input/event11

How can I do this in C++?

exebook
  • 27,243
  • 27
  • 105
  • 196
  • possible duplicate of [Parse (split) a string in C++ using string delimiter (standard C++)](http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – Ricky Mutschlechner Jan 16 '14 at 19:14

2 Answers2

1

This answer does not approach the problem in the same way. I don't think it's very efficient to split up the entire string into an array, then recombine that same array with the first element missing. So why not simply find the 2nd occurrence of '/'? With that mind:

#include <string>
#include <iostream>

using namespace std;

int main(int argc,char *argv[])
{
   string s = "/dev/input/event11";
   int index = 0,num_slash = 0;

   for(string::iterator i = s.begin();i != s.end() && num_slash < 2;i++,index++)
   {
      if(*i == '/') num_slash++;
   }
   cout << s.substr(index) << endl;
}
waTeim
  • 8,505
  • 2
  • 32
  • 37
0

Based on the idea of waTeim, but using standard functions:

int main()
{
   string s = "/dev/input/event11";
   // Find second slash.
   int num_slash = 0;
   auto iter = std::find_if(begin(s), end(s), 
      [&](char c) { if(c=='/') ++num_slash; return num_slash==2; });
   if (iter != end(s) ++iter; // Don't include second /
   std::cout << std::string(iter, end(s));
}

Alternatively (not as flexible)

int main()
{
   string s = "/dev/input/event11";
   auto iter = std::find(begin(s), end(s), '/');
   if (iter != end(s)) {
      iter = std::find(++iter, end(s), '/');
      if (iter != end(s) {
         std::cout << std::string(++iter, end(s));
      }
   }
}
MSalters
  • 159,923
  • 8
  • 140
  • 320