c++查找首尾字母相同的单词,并按字母顺序对它们进行排序

C++ find words with first and last same letter and sort them in alphabetical order

本文关键字:顺序 排序 单词 查找 c++      更新时间:2023-10-16

我不能编写程序从文件中读取首尾字母相同的单词(没有单词或长度限制)。我使用类和对象,首先我不能读取它们

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
class Texts{
public:
    void Realding(string &All);
    void Searching(string &text, char *Word);
};
int main()
{
    Texts A;
    string Text; char word[40];
    A.Reading(Text);
    A.Searching(Text, word);
    system("PAUSE");

}
void Texts::Reading(string &All)
{
    string temp;
    ifstream read("Text.txt");
    while (getline(read, temp)) { All += temp; All += "n"; }
    cout << All;
}
void Texts::Searching(string &text, char *Word)
{
    int i = 0;
    int j = 0;
    int letters = 0;
    int zodz = 0;
    int index = 0;
    while (1)
    {
        if (text[i] == ' ' || text[i] == '')
        {
            zodz++;
            if (text[0] == text[i - 1])
            {
                letters = j;
                for (int l = 0; l < letters; l++)
                {
                    //cout << text[l];
                }
                j = 0;
            }
            if (text[i + 1 - j] == text[i - 1])
            {
                letters = j;
                for (int l = i - j; l < letters; l++)
                {
                //  cout << text[l];
                }
                j = 0;
            }

        }
        if (text[i] == '') break;   
        else
        i++;                           
        j++;
    }
}

我不能使它正确地从文件中读取…Text.txt看起来像

asdfa su egze hah ktis faf

以及当选择首字母和尾字母相同的单词时,如何将其赋值给数组,以及如何将其按字母顺序排序。

读取文件:

std::ifstream in(NameOfFile);
std::string word;
while (in >> word) //will stop when word can't be read. probably bad file or end of file
{
    // do something with word
}

查找首尾字母相同的单词

if (word.front() == word.back())
{
    // do something with word
}

注意,这不适用于大写字母的单词。它找不到"妈妈"。它可能会因为空洞的话语而崩溃。

给数组赋字

array[index++] == word;

这假设您希望在插入到数组后推进索引。请注意,如果数组过满,程序将表现不佳。如果作业允许,请考虑使用std::vector

对数组排序

std::sort(array, array + index);

假设允许使用std::sort。同样,如果可能的话,使用std::vector代替阵列。假定index为上述加法示例中所有加法完成后的索引值。如果你不允许使用std::sort,问另一个问题。这是个很长的话题。