Дана строка символов. Признак конца строки — символ
'n' (переход на новую строку). Строка состоит из слов, которые отделены друг от друга пробелами. Вывести самое длинное слово и его порядковый номер.Задание аналогично задаче поиска самого короткого слова в строке. Для решения этой задачи прочитайте статью — о строках в С++. Определить символ пробела в строке можно с помощью функции isspace. Чтобы определить длину слова, воспользуйтесь функцией strlen. Пример вывода программы:
Ниже приведен код для этой задачи. Код самый простой и может усовершенствоваться (например разбиение его на несколько отдельных функции). Код нам предоставил пользователь — Василий Шуверов. Скажем ему: «Спасибо!».
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[100000];
int number [10000];
char a;
int i,j=0,n=0,k=0, g, max=0, hulp=0, hulp_1=0;
/*Набор текста и одновременный подсчет длины каждого слова.*/
for (i=0;i<100000;++i)
{
s[i]=getchar();
if (s[i]=='n')
{
number[k]=j;
break;
}
++n;
if (s[i] != ' ')
{
++j;
}
if (s[i]==' ')
{
number[k]=j;
++k;
j=0;
}
}
printf("n");
/*Отыскание самого длинного слова и его позиции в тексте */
max=number[0];
for (g=0;g<k;++g)
{
if (number[g]>max)
{
max=number[g];
hulp=g;
}
}
++hulp;
/*Вывод на экран самого длинного слова и его позиции */
printf("The longest word at number %d: ", hulp);
for (g=0;g<n;++g)
{
if (s[g]==' ')
{
++hulp_1;
}
if (hulp-hulp_1==1)
printf("%c", s[g]);
if (hulp_1>g)
break;
}
return 0;
}
Результат:
CppStudio.com
Лишь очень немногие живут сегодняшним днем. Большинство готовится жить позднее. n The longest word at number 5: сегодняшним
Комментарии
RodjeR
#include <iostream> #include <algorithm> #include <vector> #include <iterator> using namespace std; int main() { cout << "Input text = "; vector<string> vec_str (istream_iterator<string>(cin), {}); int count_alpha = 0; vector<int> long_word; int i, j; for (i = 0; i < vec_str.size(); ++i) { count_alpha = 0; for (j = 0; j < vec_str[i].length(); ++j) { count_alpha++; } long_word.push_back(count_alpha); } cout << "Most long word = " << vec_str[distance(long_word.begin(), find(long_word.begin(),long_word.end(), *max_element(long_word.begin(),long_word.end())))]; return 0; }AndreiST
#include <iostream> #include <cctype> #include <cstring> using namespace std; int main() { char character, str[] = "Only very few live for today. Most are preparing to live later. /n"; int poz=0, longer=0, counter=0, ix=0; string temp, l_world; while (str[ix]){ character = str[ix]; temp+=str[ix]; if(isspace(character)){ counter++; int max_world=temp.length(); if(max_world>longer){ l_world=temp; poz=counter; longer=max_world; } temp.clear(); } ix++; } cout << "The longest word at number " << poz << ": " << l_world << endl; return 0; }YourSpace_tym
// ConsoleApplication4.cpp : Defines the entry point for the console application. // created by YourSpace_tym #include "stdafx.h" #include "iostream" #include "string" using namespace std; int main() { string line; cout << "String : "; getline(cin, line); int rp = 0; int sp = 0; int count_of_symbols = 0; int max = 0; int word_num = 0; int word_m = 0; for (int i = 0; i < line.length(); i++) { if ((((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) || ((line[i] == '\'') && (((line[i+1] >= 'a' && line[i] <= 'z') || (line[i+1] >= 'A' && line[i] <= 'Z')))))) count_of_symbols++; if (count_of_symbols > max && ((i + 1 == line.length()) || (line[i + 1] == ' ' || line[i + 1] == '.' || line[i + 1] == '!' || line[i + 1] == '?'))) { max = count_of_symbols; sp = i; rp = sp - count_of_symbols+1; word_m = word_num + 1; } if ((i + 1 == line.length()) || (line[i + 1] == ' ' || line[i + 1] == '.' || line[i + 1] == '!' || line[i + 1] == '?')) { count_of_symbols = 0; word_num++; } } cout << "Max is " << word_m << " : "; for (int i = rp; i <= sp; i++) { cout << line[i]; } cout << endl; return 0; }