2010-02-04 179 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簡化您的循環作爲第一步。