如何将一个字符串的三个字符放入一个数组

时间:2015-11-17 19:09:11

标签: c++ arrays string

我试图将字符串rid_of_spaces中的三个字符放入数组三元组的一个空格中,但cout没有意义。

另外,我试图将三元组改为动态数组,以防三卦空间不足,但我不知道何时应该扩大容量。

//global variable
const int CAPACITY = 1000;

int main()
{
    //a string that reads in the language of the text
string language = "";
    //a string that reads in the file name of the text
string filename = "text.txt";
    //a string that reads in the original text characters
string original = "";
    //a string that reads in the modified original array
string rid_of_spaces = "";
    //an array with capacity that stores the trigrams
string trigrams[CAPACITY];
ifstream finput;
char c;
    //the length of an array
int sLength = 0;
    //the tracker for trigrams
int counter = 0;

cin >> language >> filename;
finput.open(filename.c_str());

while (finput.get(c)){
            //to test if the character is alpha
    if (isalpha(c)){
                    //change the alphabet to lowercase
        c = tolower(c);
                    //store the modified letter in the array
        original += c;
    }
            //change any other characters into a space
    else original += ' ';
}
sLength = original.length();

    //loop through the original array and change mutiple spaces into one 
for (int i = 0; i < sLength; i++){
    if (isalpha(original[i]))
        rid_of_spaces += original[i];
    else {
        while (original[i] == ' ')
            i++;
        rid_of_spaces += ' ';
        rid_of_spaces += original[i];
    }
}
sLength = rid_of_spaces.length();

for (int i = 0; i < CAPACITY; i++)
    trigrams[i] = "";//initialize each element

for (int i = 0; i < sLength - 2; i++){
    trigrams[counter] += rid_of_spaces[i] 
            + rid_of_spaces[i + 1]
            + rid_of_spaces[i + 2];
        counter++;
}

cout << filename << endl;

cout << original << endl;
cout << rid_of_spaces << endl;

for (int i = 0; i < counter; i++)
    cout << trigrams[i] << endl;

finput.close();
return 0;

}

1 个答案:

答案 0 :(得分:0)

  

我试图将字符串rid_of_spaces中的三个字符放入数组三元组的一个空格中,但是cout没有意义。

正如ebyrob在评论中所说,你可能想把我增加三:

for (int i = 0; i < sLength - 2; i+=3){
  

另外,我试图将trigram更改为动态数组

将其设为std::vector<str::string> trigrams;,然后在每次添加新字符串时使用trigrams.push_back(newStr)