【问题标题】:How do I access a character at an index in a stored string?如何访问存储字符串中索引处的字符?
【发布时间】:2013-06-12 00:25:18
【问题描述】:

所以,假设我这样做:

getline(cin, message);

我可以访问此消息中的第 n 个字符吗?

【问题讨论】:

  • 这是一个角色?我可以通过一个采用char my_car 数据类型的预定义函数来传递它,是吗?

标签: c++ string text


【解决方案1】:

只需使用您要访问的索引。

char ch=message[n-1]

使用n-1,因为索引从0开始。所以,n-1访问第n个元素

【讨论】:

    【解决方案2】:

    是的,您可以使用char& string::operator[] (size_t pos) (http://www.cplusplus.com/reference/string/string/operator[]/):

     char ch = message[nth-1];
    

    【讨论】:

    • 我可以在 11 分钟内接受答案。谢谢杨。你是苗族吗?
    • @Trancot 谢谢。我不是苗族。
    • @Trancot 这是我见过的最长的 11 分钟。
    猜你喜欢
    • 2012-11-25
    • 2017-04-15
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多