Reputation: 250
So I need to parse the input of the user in the following way: If the user enters
C:\Program\Folder\NextFolder\File.txt
OR
C:\Program\Folder\NextFolder\File.txt\
Then I want to remove the file and just save
C:\Program\Folder\NextFolder\
I essentially want to find the first occurrence of \
starting at the end and if they put a trailing slash then I can find the second occurrence. I can decifer first or second with this code:
input.substr(input.size()-1,1)!="/"
But I don't understand how to find the first occurrence starting from the end. Any ideas?
Upvotes: 0
Views: 427
Reputation: 6914
If your input
is of type std::string
( that I think it is ) you can search it using string::find
for normal search and string::rfind
for reverse search( end to start ) and also to check last character you don't need and you shouldn't use substr
, since it create a new instance of string just to check one character. You may just say if( input.back() == '/' )
Upvotes: 1
Reputation: 38173
This
input.substr(input.size()-1,1)!="/"
is very inefficient*. Use:
if( ! input.empty() && input[ input.length() - 1 ] == '/' )
{
// something
}
Finding the first occurrence of something, starting from the end is the same as finding the last "something", starting from the beginning. You may use find_last_of
, or rfind
Or, you may even use standard find
, combined with rbegin
and rend
*std::string::substr
creates one substring, "/"
probably creates another (depends on std::string::operator!=
), compares the two strings and destroys the temp objects.
Note that
C:\Program\Folder\NextFolder\File.txt\
is not a path to a file, it's a directory.
Upvotes: 1
Reputation: 234
If you are using C++ strings, then try the reverse iterator on the strings, to write your own logic on what is acceptable and what is not. There is a clear example in the link I provided.
From what I guessed, you are trying to store the directory name given a path which could be end with a file or a directory.
If that is the case, you are better of removing the trailing '\' and checking if it is a directory, and stop if it is, or else proceed if it is not.
Alternately, you can try splitting the string on '\' into two parts. Some related notes here.
If those are actual file names, (looks like you are using windows), so try the _splitpath function as well.
Upvotes: 0