0

Im trying to assign a piece of a string, to a new string variable. Now Im pretty new so longer, but easier to understand explanations are the best for me. Anyways, how Im trying to do it is like this:

string test = "384239572";
string u = test[4];

The full code of what im trying to do is this:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
string test = "384239572";
string u = test[4];
int i = 0;
istringstream sin(u);
sin >> i;
cout << i << endl;
return 0;
}

Though it seems to complain at the upper part that I put up there. So how can I take a small part of a string from a string, and assign it to a new string? Thanks a lot in advance! If you know any good links or anything about this, that would be appreciated too!

3 Answers 3

4

use substring,

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string test = "384239572";
    string u = test.substr(4,1);
    cout << u << endl;
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can use one of the string constructors

string u(1,test[4]);

EDIT: The 1 indicates the number of times to repeat the character test[4]

In your code you are trying to assign a char to a string object.

5 Comments

Okay, thanks, what does the 1 in this do though? Also can you maybe explain to me why my method doesn't work? That way I can have maximum understanding for future reference? :D
It's in the constructor documentation he linked: string ( size_t n, char c ); Content is initialized as a string formed by a repetition of character c, n times.
So when I use test[] it becomes a char and is no longer a string?
Also I noticed that when I do string u; u = test[1]; It works, but if I try to do it in one line it won't. Why is that?
The string assignment operator is overloaded to support assinging a char to a string.
2

The string class has a method substr() that would be useful here:

// Substring consisting of 1 character starting at 0-based index 4
string u = test.substr(4, 1); 

This generalizes nicely to substrings of any length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.