2016-05-17 17 views
-1

我一直在努力使這項工作一段時間。 我需要爲學校項目製作一個程序,該程序需要一個字符串並計算其中的對稱字。如何在字符串中找到對稱字?

裏面應該有句子,但任何幫助。無論我嘗試什麼方法,我似乎無法讓它工作。你能幫我嗎?

編輯:我當前的代碼

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. 
+3

如果您不提供任何代碼,幫助是可疑的。 – doug65536

+0

對不起,添加了我的當前代碼 – Piskot

回答

0

你嘗試一次做的一切!編程通常是將一個大問題分解成多個更簡單的問題的練習。

你真的只需要檢查每個單詞末尾的對稱單詞。我建議有一個代表當前單詞的字符串。當你遇到輸入中的每個字符時,看看它是否是空格。如果不是空格,請將該字符附加到currentWord字符串變量中。

每次遇到空間時,應檢查currentWord的對稱性,然後清除currentWord變量。

你的代碼試圖單獨跟蹤單詞的長度。這是要求錯誤。您可以使用length函數詢問字符串當前的長度。

所以,你的代碼應該歸結到這一點:

注意,這是僞帕斯卡 - 我想不是交給你一個複製粘貼的答案,所以你將學習

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 

...並添加一個名爲wordIsSymmetrical的函數,該函數只檢查我們傳遞給它的字符串參數。

請注意,最後你可能會有一個詞沒有遇到空間。您也可以使用wordIsSymmetrical進行檢查。

這似乎更容易做到嗎?

+0

在輸入末尾添加了一個單詞的情況處理,之後沒有空格。 – doug65536

+0

這對我非常有幫助。我真的很感謝你花時間寫下來。是的,這很容易。改變了一點,因爲它將成爲句子,而不僅僅是單詞,一個字符不是我正在尋找的。真的再次感謝你。再次抱歉沒有立即添加我的代碼。 – Piskot

+0

這個僞代碼不會查找一個字符,它每次只查看一個字符,循環遍歷整個句子。它假設單詞之間用空格分隔,所以每次遇到單詞時,就是檢查從前面的單個字符組合的單詞是否是對稱的(不管可能是 - 字謎?)。 –