I have an array of strings, and need to grab substrings (the strings in between commas, in this case) and put them into another array of strings.
I declare it as strings[numberOfTapes]
, so when I am searching for the commas I go character by character in a nested for loop, like so:
for(int j = 0; j < tapes[i].length(); j++){
if(tapes[i][j] == ','){
input[counter2] = tapes[i][j].substr(i-开发者_运维技巧counter, counter);
}
}
For which I get the following error:
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'
I'm going through the string character by character with j
. Is there a way to get .substr
to work with the tapes[i][j]
format, or do I need to implement this differently to work?
tapes[i][j]
is the character ','
, and that character has no substr
method. You probably wanted to call substr
on the string object tapes[i]
, not on the single character.
Also: You call substr(i-counter, counter)
after you found a comma at position j
. Is that your intention?
If it's an array of strings, tapes[i][j] will access a char, not the string that you wish to substring, you probably want tapes[i].substr...
If comma(,) is used as a delimiter in your case, why not using some function which splits the strings based on a delimiter?
I can think of using something like strtok() function to split them based on comma(,).
Rakesh.
Using higher-level tools rather than individually iterating each string in a sequence of strings:
#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;
}
Also look at std::string's various methods (it has a lot, described as "too many plus the kitchen sink"), you can use find to simplify your loop as a first step.
精彩评论