Найдите самое длинное и самое короткое слово в заданном предложении — Pascal(Паскаль)/C++(Си)

Pascal

var
    s : String;
    wrd : String = '';
    maxS : String = '';
    minS : String = '';
begin
    ReadLn(s);
    WriteLn(s);
    s := s + ' ';
    while (s[1] = ' ') do
        Delete(s, 1, 1);
    //вырезаем первое слово
    while (s[1] <> ' ') do
    begin
        wrd := wrd + s[1];
        Delete(s, 1, 1);
    end;
    Delete(wrd, 1, 1);
    maxS := wrd; minS := wrd;
    //вырезаем последующие и сравниваем
    while (Length(s) > 0) do
    begin
        wrd := '';
        while (s[1] <> ' ') do
        begin
            wrd := wrd + s[1];
            Delete(s, 1, 1);
        end;
        Delete(s, 1, 1);
        if (wrd <> '') then
        begin
            if (Length(maxS) < Length(wrd)) then
                maxS := wrd;
            if (Length(minS) > Length(wrd)) then
                minS := wrd;
        end;
    end;
    WriteLn('Max : ', maxS);
    WriteLn('Min : ', minS);
end.

С++

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
 
int main()
{
    std::string line;
    std::getline(std::cin, line);
    std::istringstream ist(line);
    using input_it = std::istream_iterator<std::string>;
    const auto p = std::minmax_element(input_it(ist), input_it(), [](const auto &s1, const auto &s2) { return s1.size() < s2.size(); });
    std::cout << *p.first << " " << *p.second;
}

Следующий вариант

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
 
int main() {
 char s[100];
 printf("vvedi predlojenie\n");
 gets_s(s);
 int n = strlen(s);
 int len = 0;
 int maxlen = 0;
 int pos = 0;
 for (int i = 0; i < n; i++) {
  char c = s[i];
  if (c == ' ') { //или дописать другие разделители в условие
   if (len>maxlen) { 
    maxlen = len; pos = i; 
   }
   len = 0;
  }
  else {
   len++;
  }
 }
 if (len>maxlen) { //если последнее слово - ответ
  maxlen = len; pos = n - maxlen;
 }
 cout << "Maxlen=" << maxlen << endl;
 for (int i = 0; i < n; i++) {
  char c = s[i];
  if (c == ' ') { //или дописать другие разделители в условие
   if (len == maxlen) {
     for (int j=i-maxlen; j<i; j++) cout << s[j];
     cout << endl;
   }
   len = 0;
  }
  else {
   len++;
  }
 }
 if (len == maxlen) {
  for (int j = n - maxlen; j<n; j++) cout << s[j];
 }
 getchar();
 return 0;
}

Leave a Comment

81 + = 91