C++ 如何访问 std::string 的每个成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4965767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access each member of a std::string?
提问by balasaheb
How can I access each member in a std::string variable? For example, if I have
如何访问 std::string 变量中的每个成员?例如,如果我有
string buff;
suppose buff
conatains "10 20 A"
as ASCII content. How could I then access 10, 20, and A separately?
假设buff
conatains"10 20 A"
为ASCII内容。我如何才能分别访问 10、20 和 A?
回答by jmq
Here is an answer for you on SO:
这是您在 SO 上的答案:
How do I tokenize a string in C++?
There are many ways to skin that cat...
有很多方法可以给那只猫剥皮...
回答by user607455
You can access the strings by index. i.e duff[0], duff[1] and duff[2].
您可以通过索引访问字符串。即 duff[0]、duff[1] 和 duff[2]。
I just tried. This works.
我刚试过。这有效。
string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;
It outputs "H"
它输出“H”
回答by Marlon
Well I see you have tagged both C and C++.
好吧,我看到您同时标记了 C 和 C++。
If you are using C, strings are an array of characters. You can access each character like you would a normal array:
如果您使用 C,则字符串是一个字符数组。您可以像访问普通数组一样访问每个字符:
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:
如果您使用 C++ 并使用字符数组,请参见上文。如果您使用 a 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)
{
}
or:
或者:
char c = duff.at(i); // where i is the index; the same as duff[i]
char c = duff.at(i); // where i is the index; the same as duff[i]
and probably more.
可能更多。