开发者

How to access each member of a std::string?

How can I access each member in a std::string variable? For example, if I have

string buff;

suppose buff conatain开发者_JAVA技巧s "10 20 A" as ASCII content. How could I then access 10, 20, and A separately?


Here is an answer for you on SO:

How do I tokenize a string in C++?

There are many ways to skin that cat...


You can access the strings by index. i.e duff[0], duff[1] and duff[2].

I just tried. This works.

string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;

It outputs "H"


Well I see you have tagged both C and C++.

If you are using C, strings are an array of characters. You can access each character like you would a normal array:

char a = duff[0];
char b = duff[1];
char c = duff[2];

If you are using C++ and using a character array, see above. If you are using a std::string (this is why C and C++ should be tagged separately), there are many ways you can access each character in the string:

// std::string::iterator if you want the string to be modifiable
for (std::string::const_iterator i = duff.begin(); i != duff.end(); ++i)
{
}

or:

char c = duff.at(i); // where i is the index; the same as duff[i]

and probably more.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜