如何访问std::string变量中的每个成员?例如,如果我有
string buff;假设buff将"10 20 A"作为ASCII码内容。我如何才能分别访问10、20和A?
发布于 2011-02-11 13:03:44
发布于 2011-02-11 13:02:30
您可以通过索引来访问字符串。即duff、duff1和duff2。
我刚试过了。这是可行的。
string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;它输出"H“
发布于 2011-02-11 13:09:01
我看到你已经标记了C和C++。
如果您使用的是C,则字符串是一个字符数组。您可以像访问普通数组一样访问每个字符:
char a = duff[0];
char b = duff[1];
char c = duff[2];如果您使用的是C++和字符数组,请参见上文。如果您使用的是std::string (这就是为什么C和C++应该分开标记),有许多方法可以访问字符串中的每个字符:
// std::string::iterator if you want the string to be modifiable
for (std::string::const_iterator i = duff.begin(); i != duff.end(); ++i)
{
}或者:
char c = duff.at(i); // where i is the index; the same as duff[i]
可能还有更多。
https://stackoverflow.com/questions/4965767
复制相似问题