【问题标题】:Using string functions (.substr) on arrays of strings在字符串数组上使用字符串函数 (.substr)
【发布时间】:2010-02-04 03:57:24
【问题描述】:

我有一个字符串数组,需要获取子字符串(在本例中是逗号之间的字符串)并将它们放入另一个字符串数组中。

我将其声明为strings[numberOfTapes],因此当我搜索逗号时,我会在嵌套的 for 循环中逐个字符地查找,如下所示:

for(int j = 0; j < tapes[i].length(); j++){
   if(tapes[i][j] == ','){
      input[counter2] = tapes[i][j].substr(i-counter, counter);
   }
}

我收到以下错误:

对 tapes[i].std::basic_string::operator[] 中成员 'substr' 的请求
[与 _CharT = char,_Traits = std::char_traits,_Alloc = std::allocated]
(((long unsigned int)))',属于非类类型'char'

我正在使用j 逐个字符地遍历字符串。有没有办法让.substr 使用tapes[i][j] 格式,还是我需要以不同的方式实现它才能工作?

【问题讨论】:

    标签: c++


    【解决方案1】:

    tapes[i][j] 是字符',',并且该字符没有substr 方法。您可能想在字符串对象 tapes[i] 上调用 substr,而不是在单个字符上。

    另外:在<b>j</b> 位置找到逗号后,您调用substr(<b>i</b>-counter, counter)。这是你的意图吗?

    【讨论】:

      【解决方案2】:

      如果它是一个字符串数组,则 tapes[i][j] 将访问一个字符,而不是您希望作为子字符串的字符串,您可能想要 tapes[i].substr...

      【讨论】:

        【解决方案3】:

        如果在您的情况下使用逗号(,)作为分隔符,为什么不使用一些基于分隔符分割字符串的函数呢?

        我可以考虑使用类似 strtok() 的函数来根据逗号 (,) 拆分它们。

        拉克什。

        【讨论】:

          【解决方案4】:

          使用更高级别的工具,而不是单独迭代字符串序列中的每个字符串:

          #include <iostream>
          #include <sstream>
          #include <string>
          #include <vector>
          
          int main() {
            using namespace std;
            istringstream input ("sample,data,separated,by,commas");
            vector<string> data;
            for (string line; getline(input, line, ',');) {
              data.push_back(line);
            }
          
            cout << "size: " << data.size() << '\n';
            for (size_t n = 0; n != data.size(); ++n) {
              cout << data[n] << '\n';
            }
            return 0;
          }
          

          另外看看std::string的各种方法(它有很多,被描述为“太多加上厨房水槽”),你可以使用find来简化你的循环作为第一步。

          【讨论】:

            猜你喜欢
            • 2023-02-25
            • 1970-01-01
            • 1970-01-01
            • 2021-05-13
            • 1970-01-01
            • 2022-01-14
            • 1970-01-01
            • 2015-04-02
            • 1970-01-01
            相关资源
            最近更新 更多