Упорядочьте слова заданного предложения по возрастанию количества букв. Затем слова с одинаковым количеством букв упорядочьте по алфавиту (лексикографически) — Pascal(Паскаль)/Delphi(Делфи)/C(Си)

Язык программирования Pascal

var
  q: array[1..1000] of integer;
  i, k, j, tmp: integer;
  s, a: string;
  w: array[1..1000] of string;
 
begin
  readln(s);
  for i := 1 to length(s) do
  begin
    if s[i] <> ' ' then a := a + s[i];
    if (s[i] = ' ') or (i = length(s)) then 
    begin
      inc(k);
      w[k] := a;
      q[k] := length(a);
      a := '';
    end;
  end;
  for i := 1 to k - 1 do
    for j := 1 to k - 1 do
      if q[j] > q[j + 1] then
      begin
        tmp := q[j]; a := w[j];
        q[j] := q[j + 1]; w[j] := w[j + 1];
        q[j + 1] := tmp; w[j + 1] := a;
      end;
  for i := 1 to k do writeln(w[i]);
end.

Язык программирования Delphi

        
program Project1;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
System.SysUtils;
 
var
  q: array[1..1000] of integer;
  i, k, j, tmp: integer;
  s, a: string;
  w: array[1..1000] of string;
 
 
begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    readln(s);
    for i := 1 to length(s) do
    begin
      if s[i] <> ' ' then
        a := a + s[i];
      if (s[i] = ' ') or (i = length(s)) then
      begin
        inc(k);
        w[k] := a;
        q[k] := length(a);
        a := '';
      end;
    end;
    for i := 1 to k - 1 do
      for j := 1 to k - 1 do
        if q[j] > q[j + 1] then
        begin
          tmp := q[j];
          a := w[j];
          q[j] := q[j + 1];
          w[j] := w[j + 1];
          q[j + 1] := tmp;
          w[j + 1] := a;
        end;
    for i := 1 to k do
      writeln(w[i]);
    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Следующий вариант программы

procedure TForm1.Button1Click(Sender: TObject);
var t:TStringList;
    n,i,j:integer;
    s:string;
begin
//список слов из строки, разделенных пробелами
t:=TStringList.Create;
t.DelimitedText:=Edit1.Text;
//сортировка списка по длине слов
n:=t.Count;
for i:=0 to n-2 do
for j:=i+1 to n-1 do
if length(t[i])>length(t[j]) then
 begin
  s:=t[i];
  t[i]:=t[j];
  t[j]:=s;
 end;
//вывод отсортированной строки
Label1.Caption:='';
for i:=0 to t.Count-1 do
Label1.Caption:=Label1.Caption+t[i]+' ';
t.Free;
end;

Язык программирования С

#include <stdio.h>
#include <string.h>
 
int main()
{
    char *tmp;
    char stroka[200];
    char mas[10][10];
    char temp[10];
 
    int i,j,word_count=0;
 
    printf("Enter string: ");
    gets(stroka);
 
    tmp = strtok(stroka, " ");
    for (i = 0; tmp != '\0'; i++)
    {
        strcpy(mas[i], tmp);
        tmp = strtok(NULL, " ");
        word_count++;
    }
 
    //sort
    for(i = 0 ; i < word_count ; i++)
    {
        for(j = 0 ; j < word_count - i - 1 ; j++)
        {
            if(strlen(mas[j])>strlen(mas[j+1]))
            {
                strcpy(temp,mas[j+1]);
                strcpy(mas[j+1],mas[j]);
                strcpy(mas[j],temp);
            }
        }
    }
 
    for(i=0; i<word_count; i++)
        printf("%s ",mas[i]);
 
    return 0;
}

Следующий вариант программы

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
 
int
compareStrings(const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strlen(*ia) - strlen(*ib);
}
 
char*
duplicateString(const char* str)
{
    if (!str || !*str) {
        return NULL;
    }
    size_t len = strlen(str) + 1;
    char* dupl = malloc(len);
    memset(dupl, 0, len);
    strcpy(dupl, str);
}
 
size_t
countWords(const char* str)
{
    if (!str) {
        return 0;
    }
    size_t cnt = 0;
    for ( ; *str; ++str) {
        if (isspace(*str)) {
            ++cnt;
        }
    }
    return cnt + 1;
}
 
struct Tokens { /* Interesting, how to put the fields here for better aligning? */
    char** tokens; /* tokens which are stored in the string, ends in NULL */
    char* string; /* to malloc and free memory for string copy */
    size_t len;
};
 
struct Tokens
getTokensFromString(const char* src, const char* delim)
{
    struct Tokens tokens = {.tokens = NULL, .string = NULL, .len = 0};
    if (!(tokens.string = duplicateString(src))) {
        exit(EXIT_FAILURE);
    }
    if (!(tokens.len = countWords(tokens.string))) {
        exit(EXIT_FAILURE);
    } /* + 1 for NULL terminator */
    if (!(tokens.tokens = malloc(sizeof(*tokens.tokens) * (tokens.len + 1)))) {
        exit(EXIT_FAILURE);
    }
    memset(tokens.tokens, 0, tokens.len + 1);
    size_t i = 0;
    tokens.tokens[ i ] = strtok(tokens.string, delim);
    while (tokens.tokens[ i++ ]) {
        tokens.tokens[ i ] = strtok(NULL, delim);
    }
    return tokens;
}
 
int
main(int argc, char** argv)
{
    const char* sentense = "this is a sentense with words and other stuff";
    struct Tokens tokenized_sentense = getTokensFromString(sentense, " ");
    char** iter = tokenized_sentense.tokens;
    puts("Tokens:");
    printf("%zu\n", tokenized_sentense.len);
    for ( ; *iter; ++iter) {
        printf("%s\n", *iter);
    }
    qsort(tokenized_sentense.tokens, tokenized_sentense.len,
          sizeof(char*), compareStrings);
    puts("Sorted tokens:");
    iter = tokenized_sentense.tokens;
    for ( ; *iter; ++iter) {
        printf("%s\n", *iter);
    }
    free(tokenized_sentense.string);
}

Leave a Comment

93 − = 88