I've been trying to make this work for a while now.
I need to make a program for school project that takes a string and counts symmetrical words inside it.
There are supposed to be sentences inside, but anything helps. I can't seem to get it to work no matter what approach I try. Could you help me out?
EDIT: my current code
write('Enter text: ');readln(text);
if text<>'' then
for i:=1 to length(text) do
if space then
if text[i]<>' ' then
if space then
for j:=1 to length(word) do
if drow[k]<>word[j] then sym:=false;
if space and sym then p1:=p1+1;
else writeln('You didnt enter any text');
writeln('there are ',p1,' symmetrical words in text');
You try to do everything at once! Programming is often an exercise in breaking a big problem down into multiple easier problems.
You really only need to check for a symmetrical word at the end of each word. I suggest having a string that represents the current word. As you encounter each character in the input, see if it is a space. If it is not a space, append that character to a
currentWord string variable.
Every time you encounter a space, you should check
currentWord for symmetry, then clear the
Your code tries to separately keep track of the length of the word. This is asking for bugs. You can ask the string for its current length, using the
So your code should boil down to this:
Note that this is pseudo-Pascal - I am trying not to hand you a copy-paste answer so you will learn
currentWord := '' for each character do begin if this character is not a space then add the character to the currentWord else if wordIsSymmetrical(currentWord) then print word or add to count as needed end currentWord := '' end end if currentWord <> '' then if wordIsSymmetrical(currentWord) then print word or add to count as needed end end
...and add a function called
wordIsSymmetrical which only checks the string parameter that we pass to it.
Note that at the end you may have a word without encountering a space. Here again you can use
wordIsSymmetrical to check .
Does that seem easier to do?