开发者

C++ assign element of a string to a new string

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 s开发者_运维问答tring? Thanks a lot in advance! If you know any good links or anything about this, that would be appreciated too!


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜