【问题标题】:substr to char c++ no arraysubstr 到 char c++ 没有数组
【发布时间】:2016-09-14 06:11:56
【问题描述】:

正如标题所说,我正在尝试将 substr 转换为 char。最终我要做的是用 substr 告诉它是一个大写或小写字母,我得到的提示是最好的方法是使用 ascii 值。这就是我所拥有的

for(int i = 0; i<length; i++){
  char a = a.substr(i,1);
 if(a>=65&&a<=90){
   uppercase++;
 }
}

我在这里收到此错误:

string_info.cpp:34:16: error: member reference base type 'char' is not a
      structure or union
     char a = a.substr(i,1);

我知道它不起作用,因为 substr 输出的是字符串而不是字符,但我不明白如何获取这些 ascii 值。有人有什么想法吗?

【问题讨论】:

  • substr 将返回一个std::string,而不是一个字符。您可以将 substr 与 [ ] 运算符结合使用,也可以直接在源字符串上使用它...
  • if (a&gt;=65&amp;&amp;a&lt;=90) --> if( (a&gt;='A') &amp;&amp; (a&lt;='Z') )
  • @Blacktempel 不会让它成为一个数组吗?我试图避免使用数组。
  • a 是 char 类型,substr 是使用字符串对象调用的函数。
  • 你能详细说明你的问题吗?

标签: c++ substring


【解决方案1】:

为什么还要使用 substr?您的代码基本上只是逐个字符地遍历字符串。为此,您可以使用 []at

for (int i=0;i<a.length();i++) {
    char c = a[i];
    /*
        Can also use
        char c = a.at(i);
     */

    if (c >= 'A' && c <= 'Z') {
        uppercase++;
    }
}

还要注意您的char a = a.substr(i, 1); 代码是错误的,因为substr 返回一个string,并且您还重新声明了a

【讨论】:

  • 我尝试了 a.at(i) 并得到了 string_info.cpp:34:16: 错误:成员引用基类型 'char' 不是结构或联合 char a = a.at(i );
  • 你犯了和以前一样的错误。看我写的代码。它是char c = a.at(i);。您使用的是char a = a.at(i);,这是错误的。
  • 天哪。非常感谢,我已经坚持了几个小时。非常感谢@MobileBen
【解决方案2】:

我建议使用基于范围的 for 循环,而不是使用 substr、at 或 operator[]:

  std::string a = "Test";
  int uppercase = 0;
  for(const auto& c : a)
  {
    if (c >= 'A' && c <= 'Z')
      uppercase++;
  }

而且,与其使用 ASCII 值,不如使用 isupper 函数:

  std::string a = "Test";
  int uppercase = 0;
  for (const auto& c : a)
  {
    if(isupper(c))
      uppercase++;
  }

【讨论】:

  • 大声笑,我会建议但不确定他是否使用 C++11
  • 呵呵,我用 C++11 回答,因为他没有具体说明他在使用什么,而且还没有这样的答案。无论如何,我认为如果他可以使用 C++/C++14,他应该这样做。
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2013-09-13
  • 2021-01-26
相关资源
最近更新 更多