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

how to put three characters of a string into one space of an array

本文关键字:数组 一个 空间 字符 三个 字符串      更新时间:2023-10-16

我试图将字符串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;

}

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

正如ebyrob在评论中所建议的那样,您可能希望将i增加三:

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

此外,我试图将三元图更改为动态阵列

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

相关文章: