2

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

string buff;

suppose buff conatains "10 20 A" as ASCII content. How could I then access 10, 20, and A separately?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
balasaheb
  • 21
  • 1
  • 1
  • 2
  • 1
    well "10" is not a character in its string representation, it is two characters. Are you asking how to split a string? – Ed S. Feb 11 '11 at 05:02
  • 1
    Well, ⒑ is U+2491 but that's not ASCII ;) – MSalters Feb 11 '11 at 07:26
  • @Eds n @Msalterd , yes i know that 10 is int but i put that int into string – balasaheb Feb 11 '11 at 08:11
  • I didn't say ten is an int, I said that the string "10" consists of two characters. You ask *How can I access each member in a std::string variable*, from which I assume you are asking how to access the string character by character. You then go on to say that "10" should be considered as a single "element", so the questions doesn't make much sense. – Ed S. Feb 11 '11 at 08:22

3 Answers3

5

Here is an answer for you on SO:

How do I tokenize a string in C++?

There are many ways to skin that cat...

Community
  • 1
  • 1
jmq
  • 10,110
  • 16
  • 58
  • 71
3

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"

user607455
  • 479
  • 5
  • 18
1

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.

Marlon
  • 19,924
  • 12
  • 70
  • 101
  • @Marlon- I don't think this answers the OP's question. This will hand back individual characters, rather than the integer literals made up by those characters. – templatetypedef Feb 11 '11 at 05:44