Help in Pascal writing a word counter
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.
source to share
(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.
source to share
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?
source to share