Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the second largest word in a string with Pascal

1 Answer

0 votes
program SecondLargestWordProgram;

uses
  SysUtils;

function FindSecondLargestWord(s: string): string;
var
  words: array of string;
  i, j: Integer;
  temp: string;
begin
  s := s + ' ';
  SetLength(words, 0);

  // Split the string into words
  while Pos(' ', s) > 0 do
  begin
    SetLength(words, Length(words) + 1);
    words[High(words)] := Copy(s, 1, Pos(' ', s) - 1);
    Delete(s, 1, Pos(' ', s));
  end;

  // Sort the words by length in descending order
  for i := 0 to High(words) - 1 do
    for j := i + 1 to High(words) do
      if Length(words[j]) > Length(words[i]) then
      begin
        temp := words[i];
        words[i] := words[j];
        words[j] := temp;
      end;

  // Return the second largest word
  if Length(words) < 2 then
    FindSecondLargestWord := ''
  else
    FindSecondLargestWord := words[1];
end;

var
  str, secondLargestWord: string;
begin
  str := 'c cpp cobol c# pascal java';
  secondLargestWord := FindSecondLargestWord(str);

  if secondLargestWord <> '' then
    Writeln('The second largest word is: ', secondLargestWord)
  else
    Writeln('There are not enough words in the string.');
end.



(*
run:

The second largest word is: cobol

*)

 



answered Jan 19, 2025 by avibootz
...