2012-12-12 56 views
1

好吧,所以我創建了一個程序來定義插入的詞是否是迴文。 但我需要幫助刪除數字,在哪裏插入字符串。在java中刪除插入的數字字符串

import java.util.*; 
import java.util.Scanner; 
class Palindrome 
{ 
    public static void main(String args[]) 
    { 
     String reverse = ""; 
     Scanner scan = new Scanner(System.in); 
     System.out.print("Type a sentence and press enter: "); 
     String input = scan.nextLine(); 
     // use regex to remove the punctuation and spaces 
     String Input = input.replaceAll("\\W", " "); 
     System.out.println(Input); 

     int length = input.length(); 

     for (int i = length - 1 ; i >= 0 ; i--) 
     reverse = reverse.replaceAll("\\W", "") + input.charAt(i); 
     System.out.println(reverse); 

     if (input.equals(reverse)) 
     System.out.println("Entered string is a palindrome."); 
     else 
     System.out.println("Entered string is not a palindrome."); 
    } 
} 
+5

這不是一個問題。請儘量詳細說明你的問題。 – Yaniv

+1

你總是在'else'部分輸入一個輸入作爲'句子'。 YOu正在使用修改輸入的相反方向檢查原始輸入。重新檢查你想要的是什麼?我不認爲你想檢查一個句子是否是迴文? – mtk

+0

你是什麼意思,這不是特定的。讀我寫的東西。 – Germblaster

回答

6

如果你想刪除的數字,嘗試input.replaceAll("[0-9]","")

+0

我應該把它放在哪裏? – Germblaster

+0

您可以在替換空格的標點後將其鏈接起來:String Input = input.replaceAll(「\\ W」,「」).replaceAll(「[0-9]」,「」); –

+0

好的,非常感謝你的時間。我終於搞定了。不知道你可以另一個.replaceAll聲明接連不斷。謝謝 – Germblaster

0

試試這個........

public class T1 { 

    public static void main(String[] args){ 

     String s = "1234ajhdhols233adfjal"; 

     String[] arr = s.split("\\d"); 
     String sx = new String(); 
     for(String x : arr){ 

      sx = sx+x; 
     } 

     System.out.println(sx); 
    } 

} 
0

例子:

public static void main(String[] args) { 
    String s = "1234ajhdhols233adfjal"; 
    String str = s.replaceAll("\\d", ""); 

    System.out.println(str); 
}