在字符串数组上使用字符串函数(.substr)

时间:2010-02-04 03:57:24

标签: c++

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

我将其声明为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);
   }
}

我得到以下错误:

request for member 'substr' in tapes[i].std::basic_string::operator[]
[with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocated]
(((long unsigned int)))', which is of non class type 'char'

我将使用j逐字逐句查找字符串。有没有办法让.substr使用tapes[i][j]格式,或者我需要以不同方式实现这一点吗?

4 个答案:

答案 0 :(得分:1)

tapes[i][j]是字符',',该字符没有substr方法。您可能希望在字符串对象substr上调用tapes[i],而不是在单个字符上调用。{/ p>

另外:您在位置substr(i-counter, counter)找到逗号后致电j。这是你的意图吗?

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

我可以考虑使用像strtok()函数这样的东西来基于逗号(,)来分割它们。

勒凯什。

答案 3 :(得分:0)

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

#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来简化循环作为第一步。