2010-02-04 134 views
0

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

我宣布它作为strings[numberOfTapes],所以当我寻找逗号我去逐个字符在嵌套的循环,像这样:

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。有没有办法让.substrtapes[i][j]格式一起使用,还是我需要以不同的方式实现它的工作?

回答

1

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

另请参见:您在位置j处发现逗号后请致电substr(i-counter, counter)。这是你的意图吗?

1

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

0

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

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

Rakesh。

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