Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove substring from string c++

Tags:

c++

split

token

I have a string s="home/dir/folder/name"

I want to split s in s1="home/dir/folder" and s2="name";

I did:

char *token = strtok( const_cast<char*>(s.c_str() ), "/" );
std::string name;
std::vector<int> values;
while ( token != NULL )
{
    name=token;

    token = strtok( NULL, "/" );
}

now s1=name. What about s2?

like image 220
sunset Avatar asked Dec 17 '22 11:12

sunset


2 Answers

I'd recommend against using strtok. Take a look at Boost Tokenizer instead (here are some examples).

Alternatively, to simply find the position of the last '/', you could use std::string::rfind:

#include <string>
#include <iostream>

int main() {
  std::string s = "home/dir/folder/name";
  std::string::size_type p = s.rfind('/');
  if (p == std::string::npos) {
    std::cerr << "s contains no forward slashes" << std::endl;
  } else {
    std::string s1(s, 0, p);
    std::string s2(s, p + 1);
    std::cout << "s1=[" << s1 << "]" << std::endl;
    std::cout << "s2=[" << s2 << "]" << std::endl;
  }
  return 0;
}
like image 154
NPE Avatar answered Dec 27 '22 03:12

NPE


If your goal is only to get the position of the last \ or / in your string, you might use string::find_last_of which does exactly that.

From there, you can use string::substr or the constructor for std::string that takes iterators to get the sub-part you want.

Just make sure the original string contains at least a \ or /, or that you handle the case properly.

Here is a function that does what you need and returns a pair containing the two parts of the path. If the specified path does not contain any \ or / characters, the whole path is returned as a second member of the pair and the first member is empty. If the path ends with a / or \, the second member is empty.

using std::pair;
using std::string;

pair<string, string> extract_filename(const std::string& path)
{
  const string::size_type p = path.find_last_of("/\\");

  // No separator: a string like "filename" is assumed.
  if (p == string::npos)
    return pair<string, string>("", path);

  // Ends with a separator: a string like "my/path/" is assumed.
  if (p == path.size())
    return pair<string, string(path.substr(0, p), "");

  // A string like "my/path/filename" is assumed.
  return pair<string, string>(path.substr(0, p), path.substr(p + 1));
}

Of course you might as well modify this function to throw an error instead of gracefully exiting when the path does not have the expected format.

like image 45
ereOn Avatar answered Dec 27 '22 03:12

ereOn