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
program rocnik;
var text:string;
word,drow:string[10];
i,j,k,p1:integer;
space,sym:boolean;
begin
p1:=0;
write('Enter text: ');readln(text);
if text<>'' then
begin
for i:=1 to length(text) do
begin
k:=0;
if space then
begin
j:=0;
space:=false;
end;
sym:=true;
if text[i]<>' ' then
begin
j:=j+1;
word[j]:=text[i];
end
else space:=true;
if space then
begin
space:=false;
for j:=1 to length(word) do
begin
k:=k+1;
drow[k]:=word[j];
if drow[k]<>word[j] then sym:=false;
end;
end;
if space and sym then p1:=p1+1;
end;
end
else writeln('You didnt enter any text');
writeln('there are ',p1,' symmetrical words in text');
readln;
end.
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 currentWord
variable.
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 length
function.
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?