M
Marcus Kwok
Is std::string::npos portably able to be incremented?
For example, I want to insert some text into a string. If a certain
character is found, I want to insert this text immediately after this
character; otherwise I insert at the beginning of the string. On my
implementation string::npos has the value of (string::size_type)-1, so
incrementing it will make it 0, but can I rely on it?
Also, say that the character occurs at the end of the string. Is it
valid to specify the insert position as one greater than this value?
Example usage of what I want to do is shown in fix_path(). Everything
behaves as I would expect on my implementation (VS 2005).
#include <iostream>
#include <string>
void fix_path(std::string& s)
{
using std::string;
string to_insert = "goes/";
string::size_type pos = s.rfind('/');
s.insert(pos + 1, to_insert);
}
void test(const std::string& s)
{
using std::cout;
using std::string;
string t(s);
cout << t << '\n';
fix_path(t);
cout << t << "\n\n";
}
int main()
{
using std::cout;
using std::string;
test("my/stuff/here");
test("here");
test("another/");
test("/beginning");
}
/*
Output:
my/stuff/here
my/stuff/goes/here
here
goes/here
another/
another/goes/
/beginning
/goes/beginning
*/
For example, I want to insert some text into a string. If a certain
character is found, I want to insert this text immediately after this
character; otherwise I insert at the beginning of the string. On my
implementation string::npos has the value of (string::size_type)-1, so
incrementing it will make it 0, but can I rely on it?
Also, say that the character occurs at the end of the string. Is it
valid to specify the insert position as one greater than this value?
Example usage of what I want to do is shown in fix_path(). Everything
behaves as I would expect on my implementation (VS 2005).
#include <iostream>
#include <string>
void fix_path(std::string& s)
{
using std::string;
string to_insert = "goes/";
string::size_type pos = s.rfind('/');
s.insert(pos + 1, to_insert);
}
void test(const std::string& s)
{
using std::cout;
using std::string;
string t(s);
cout << t << '\n';
fix_path(t);
cout << t << "\n\n";
}
int main()
{
using std::cout;
using std::string;
test("my/stuff/here");
test("here");
test("another/");
test("/beginning");
}
/*
Output:
my/stuff/here
my/stuff/goes/here
here
goes/here
another/
another/goes/
/beginning
/goes/beginning
*/