C ++中字符串索引的问题

时间:2013-12-31 16:21:27

标签: c++

如何在C ++中访问字符串索引? 例如:如果我有字符串变量名称测试,我想从索引号5到9访问它。我怎么能用C ++做到这一点?

string test;
cout<<test[5:9];

我尝试了上面的方法,但它不起作用。有什么建议?谢谢。

3 个答案:

答案 0 :(得分:8)

如果包含字符串库,则可以使用substr方法:

http://www.cplusplus.com/reference/string/string/substr/

cout << test.substr(5, 4)

请注意,参数是起始索引和子字符串的长度,而不是起始索引和最后一个索引。

答案 1 :(得分:1)

此切片语法在C ++中不起作用。您必须使用std::string::substr

示例:

std::string test = "Some test string";
std::cout << test.substr(5, 4) << std::endl;

答案 2 :(得分:0)

使用substr

在C ++中没有切片运算符看起来像[x:y]