c++查找首尾字母相同的单词,并按字母顺序对它们进行排序
C++ find words with first and last same letter and sort them in alphabetical order
我不能编写程序从文件中读取首尾字母相同的单词(没有单词或长度限制)。我使用类和对象,首先我不能读取它们
#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
,问另一个问题。这是个很长的话题。
相关文章:
- 在自定义程序中使用本机 Windows 自然顺序排序
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 在 C++ 中,以相反顺序排序的最快方法是什么?
- 按字母顺序排序字符数组,然后按长度排序
- 按第一个值的递减顺序对一组对进行排序,然后按第二个值的字母顺序排序
- C 在向量的向量中按字母顺序排序字符串
- 双链表中按字母顺序排序的链接
- 从文件中读取并按字母顺序排序
- 按字母顺序排序阵列C
- 构造函数的初始值设定项列表中的函数调用是否按顺序排序?
- 使用指针数组按字母顺序排序
- 按字母顺序排序,带有 å ä ö
- 按字母顺序排序名称,数组错误
- 如何从对数字进行排序到按C++字母顺序排序
- 从文件C++中按字母顺序排序
- 无法实现从文件按字符串 C++ 中的字母顺序排序的函数
- 并发消息处理按时间顺序排序
- 如何在 std::vector 中查找重复项<strings>并返回一个 std::list 它们按字母顺序排序,在该结果列表中没有重复项
- C++按字母顺序排序字符串
- 按字母顺序排序JSON值