0

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..

2
  • 2
    use string::resize Commented Oct 28, 2014 at 12:08
  • 3
    Don't mix std::string and "C-style" string concepts. Commented Oct 28, 2014 at 12:12

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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); 

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.