Help in Pascal writing a word counter

I need to write a program in Pascal that should determine how many words in a text (user input) start with a specific letter. I can't use arrays, can you give me any hints on where to start?

+2


source to share


5 answers


If you know which letter you just need to keep the counter, no need for arrays.



If you don't know which letter, save 26 counters. Silly, but works as per your specification.

+3


source


The first thing to do is to determine the set of characters that make up the letters, or, conversely, which ones are non-letters.



Write a function that takes a character and returns a boolean value based on whether that character is a letter. Then loop through the line and call it for each character. When you find a letter just after a letter or at the beginning of a line, increment the counter if it is the target letter.

+1


source


count instances of SPACE LETTER plus the first word if it matches.

0


source


(S) is your input string;

  • Create a for loop that goes from 1 to length (S) - 1.
  • Inside the loop, (S) [i] = '' and (S) [i + 1] = 't' are checked, where i is the loop counter and 't' is the letter that starts with the word you want to count
  • If the criteria for the second step are the same, then increase the counter.

Note the minus on the buttonhole size.

Also, remember that the very first letter of the string might be the one you want to match and that the above loop will not pick up.

If you need to make your code smarter so that it can find a specific letter and not the hardcoded "t" then you can pass the requested character as a parameter to the function / procedure that your loop is in.

0


source


Off the top of my head - untested

function WordCount(const S: string; const C: Char): Integer;
const
  ValidChars: Set of Char [A..Z, a..z]; // Alter for appropriate language
var
  i : Integer;
  t : string;
begin
  Result := 0;
  if Length(S) <> 0 then
  begin
    t := Trim(S); // lose and leading and trailing spaces
    t := t + ' '; // make sure a space is the last char
    repeat
      if (t[1] in ValidChars) and (t[1] = C then
        inc(Result);
      i := Pos(' ', t);
      t := Copy(t(i+1, Length(t));
    until Length(t) = 0;
  end;
end;

      

Why do you need an array or a case statement?

-2


source







All Articles