小编San*_*eev的帖子

为什么我无法使用索引访问字符串单个字符

string strMap[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//string digits received as parameter in function // digits = "234";
Run Code Online (Sandbox Code Playgroud)

访问它如下:

int digitmapIndex = digits[index] - 46;   //index is some int 0,1 etc..
int mapstr_len = strMap[digitmapIndex];
Run Code Online (Sandbox Code Playgroud)

或者

int mapstr_len = strMap[digits[index] - 46];
Run Code Online (Sandbox Code Playgroud)

错误:

Line 25: Char 13: error: no viable conversion from 'std::string' (aka 'basic_string<char>') to 'int'
        int mapstr_len = strMap[digits[index] - 46];
            ^            ~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:816:7: note: candidate function
      operator __sv_type() const noexcept
Run Code Online (Sandbox Code Playgroud)

c++ string c++11

0
推荐指数
1
解决办法
69
查看次数

C char 与使用索引访问的 C++ 字符串元素有何不同

我正在使用 C++ 擦除删除习惯用法并面临一个奇怪的问题。如果我使用字符串索引访问元素,结果将不符合预期。

   string str = "A man, a plan, a canal: Panama";
   str.erase(remove(str.begin(), str.end(), str[1]), str.end());
Run Code Online (Sandbox Code Playgroud)

结果:安缦、计划、运河:帕纳

如果我按如下方式使用,结果符合预期。

   string str = "A man, a plan, a canal: Panama";
   str.erase(remove(str.begin(), str.end(), ' '), str.end());
Run Code Online (Sandbox Code Playgroud)

结果 : Aman,aplan,acanal:巴拿马

c++ string stl

0
推荐指数
1
解决办法
74
查看次数

标签 统计

c++ ×2

string ×2

c++11 ×1

stl ×1