user1840579
user1840579

Reputation: 13

How to split a phrase into words in pascal?

I have to create a program that splits phrases (with special characters such as % and $) into words using a procedure in pascal.

So if i enter:

This is a valid word: 12$%ab

The program must return me:

This
is
a
valid
word:
12$#ab

Without the spaces, one below the other.

I can't use arrays and the variable that "calls" the procedure must be a string.

Thanks in advance!

Here's my code:

program words;
uses crt;
var 
 phrase  :string;
 word:string;
 letter  :char;
 x      :integer;

begin
 clrscr;
 phrase:='';
 word:='';
 x:=1;                         
 repeat
  write('type a phrase: ');
  readln(phrase);
  until phrase<>'';
 while x<=length(phrase) do
 begin
  letter:=phrase[x];
  case letter of
   'a'..'z','A'..'Z':
    begin
     word:=word+letter;
     repeat
       x:=x+1;
       letter:=phrase[x];
       word:=word+letter;
      until (letter=' ') or (x=length(phrase));
     writeln(word);
     word:='';
    end;
  end;
  x:=x+1;
 end;
writeln;
readkey;
end.

Upvotes: 1

Views: 7233

Answers (2)

No&#39;am Newman
No&#39;am Newman

Reputation: 6477

I can't see what the problem is with the code provided (although it will fail should there be a digit in the given string), but I can see that it is inefficient - there's no need for all the string concatenation. I can see two other ways of handling the problem -

first approach - search, print and delete

repeat
 write ('type a phrase: ');
 readln (phrase);
until phrase <>'';

while phrase <> '' do
 begin
  i:= pos (' ', phrase);
  if i = 0 then
   begin
    writeln (phrase);
    phrase:= ''
   end
  else
   begin
    writeln (copy (phrase, 1, i-1));  // no need to write the terminating space!   
    phrase:= copy (phrase, i + 1, length (phrase) - i)
   end
 end;

second approach: search, print and continue

repeat
 write ('type a phrase: ');
 readln (phrase);
until phrase <>'';

j:= 1;
i:= 1;
len:= length (phrase);
repeat
 while (phrase[i] <> ' ') and (i < len) do inc (i);
 writeln (copy (phrase, j, i - 1));
 j:= i;
 inc (i)
until i > len;

Upvotes: 2

T J
T J

Reputation: 21

Loop through each character for the length of the string, check if it's a space, if it is, print the previous characters, if not, add to a variable containing previous characters.

Upvotes: 2

Related Questions