Найти в тексте слова максимальной длины и упорядочить их в алфавитном порядке С++
На С++ задали решить задачку:
Дается текст, нужно найти слова максимальной длины и упорядочить их в алфавитном порядке, можно использовать строки. Как начать программу, как идти дальше?
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
void func(ifstream&);
int main()
{
ifstream file;
file.open("text.txt");
func(file);
int sort();
file.close();
}
void func(ifstream& file) {
setlocale(LC_ALL, "rus");
int max = 0;
string word;
while (!file.eof()) {
file >> word;
while (word.find(',') != -1)
word.erase(word.find(','), 1);
while (word.find('.') != -1)
word.erase(word.find('.'), 1);
if (word.length() > max)
max = word.length();
}
file.seekg(0, SEEK_SET);
printf("\n %s %d", "Максимальная длина слова > ", max);
printf("\n %s", "Слова максимальной длины > ");
if (max == 0)
return;
while (!file.eof()) {
file >> word;
while (word.find(',') != -1)
word.erase(word.find(','), 1);
while (word.find('.') != -1)
word.erase(word.find('.'), 1);
if (word.length() == max)
cout << word << " ";
}
int sort();
{ ifstream in("text.txt");
ofstream out("output.txt");
list<string> lines;
while (!in.eof())
{
string word;
getline(in, word, '\n');
lines.push_back(word);
}
lines.sort();
copy(lines.begin(), lines.end(), ostream_iterator<string>(out, "\n"));
in.close();
out.close();
}
}
Ответы (1 шт):
Автор решения: Maggot
→ Ссылка
Вот мой взгляд (просто накидал код - разумеется много памяти и телодвижений - но прост опервый наскок)
Алгоритм -
- сепарируйте строку или файл
- вычленяете максимальное слово и берете его size
- еще раз пробегаете по строке или файлу - смотриет слвоа с тем же сайзоми прикапывайте его в любой контейнер - я взял вектор чтоб были дубликаты и тд. если они не нужны берите сразу std::set - не надо будет в таком случае делать соритровку
- если все же std::vector то еще сортируем его
Вот решение в лоб
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <vector>
int main() {
std::string line("This is the top level of the kernel’s documentation tree Kernel documentation like the kernel itself is very much a work in progress that is especially true as we work to integrate our many scattered documents into a coherent whole Please note that improvements to the documentation are welcome join the linux-doc list at if you want to help out");
std::istringstream iss(line);
auto byLenght = [&](const std::string& a, const std::string& b) {
return a.size() < b.size();
};
auto it = std::max_element(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), byLenght);
std::cout << *it << " size = " << it->size() << std::endl;
iss.clear();
iss.str(line);
std::vector<std::string> ret;
std::for_each(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), [&it, &ret](std::string s) {if (s.size() == it->size()){ret.push_back(s);}});
std::sort(std::begin(ret), std::end(ret));
for (auto v : ret) {
std::cout << v << std::endl;
}
return 0;
}