Reputation: 5924
I have made a new string using the existing string. Let say the initial string is
string a="sample";
and the newly created string is
string b=a;
Now I have placed the null character at the second index.
b[2]='\0';
when I try to out put the b string.
The output is shown as saple
.
I want to end the string after index-1.
Is this behavior normal.If it is normal how to end the string after 1st index.
Thanks..
Upvotes: 0
Views: 81
Reputation:
operator<<
is overloaded for std::string
. The behavior will differ than if you do this:
char a[] = "sample";
char b[sizeof(a)];
strcpy(b, a);
b[2] = '\0';
std::cout << b;
or std::cout << b.c_str();
(which calls the overload for a const char*
rather than a std::string
). The difference between the two overloads is that the overload for const char*
calls std::char_traits<char>::length
to determine how many characters to print (that is, up to the terminating null character). On the other hand, the overload for std::string
uses str.size()
. The size of a std::string
includes any null characters embedded in it.1
In order to "truncate" a string, you can follow @Wimmel's suggestion and use resize
:
std::string a = "sample";
std::string b = a;
b.resize(2);
std::cout << b;
1 STL basic_string length with null characters
Upvotes: 3
Reputation: 536
I'm not sure what the standard defines should happen with what you are currently doing, but the proper way to do what you are trying to achieve is using std::string::substr() method like this:
b = a.substr(0, index-1);
Upvotes: 2
Reputation: 2151
It is normal.
unlike C string, the lenght of std::string
is not determined by '\0'
, instead, there's a member variable recording its length. in the case, the string content is 73 61 00 70 6c 65
, thus, b.length() == 6
, though there's a '\0'
in it. you also can redirect the output into a file, and check the content, it is 73 61 00 70 6c 65
.
If you wanna to truncate the string, call b.resize(2)
.
Upvotes: 0