2016-09-27 41 views
-1

需要一些幫助。 所以這裏是任務: 創建一個程序,將要求一個主要的短語。詢問將在短語中保留的關鍵字符串值。顯示原始主要短語的一個版本,其中所有字符都被加號(「+」)替換,除了保留不變的密鑰字符串值外。 樣品輸出:Java替換字符串中的字符除了變量中的給定值

------------------------------------------------ 
Enter main phrase: 12xy34 
Enter key string:xy 
New Version: ++xy++ 
------------------------------------------------ 
Enter main phrase: 12xy34 
Enter key string:1 
New Version: 1+++++ 
------------------------------------------------ 
Enter main phrase: 12xy34xyabcxy 
Enter key string:xy 
New Version: ++xy++xy+++xy 

這裏是我的代碼:

import java.util.*; 
public class Corpuz_Kervin 
{ 
    public static void main (String [] args) 
    { 
     Scanner input = new Scanner (System.in); 
     String phrase,key= ""; 
     String plus = "+"; 


     System.out.print("Enter main phrase : "); 
     phrase = input.nextLine(); 
     System.out.print("Enter key string : "); 
     key = input.nextLine(); 



     for (int i = 0; i < phrase.length(); i++) 
     { 
      char x = phrase.charAt(i); 
      if (x.contains(key)) 
      { 
       System.out.print(phrase.replace(x),"+"); 
      } 
      else 
      { 
       System.out.print("Error"); 
      } 
     } 
    } 
} 

誰能幫我 感謝

+0

你應該張貼您的實際輸出。 – Jacob

+0

更好的思考方式是採用一串'+'符號,並用關鍵短語替換某些位置。找出原始字符串中出現關鍵短語的所有偏移量,並將這些偏移量添加到一串加號中。 –

回答

1

使用這個,而不是你的循環:

System.out.println(phrase.replaceAll("[^" + key + "]", plus)); 
+0

我會嘗試這 –

+0

@JohnMichaelRivera告訴我,如果它的工作原理。 – Blobonat

+0

是的!它的工作原理!順便說一句,非常感謝 –

0

爲什麼不與未phrace使用的replaceAll,用這個表達「({?!。您的短語})「

+0

uhm那麼代碼將會如何呢?我會在哪裏放置這個表達式? –

+0

import java.util。*; 公共類Corpuz_Kervin { \t公共靜態無效的主要(字串[] args) \t { \t \t掃描儀輸入=新掃描儀(System.in); \t \t String phrase,key; \t \t String plus =「+」; \t \t \t \t \t 是System.out.print \t( 「輸入主短語:」); \t \t phrase = input.next(); \t \t System.out.print(「Enter key string:」); \t \t key = input.next(); \t \t對(INT I = 0; I

0

xcharkeyString:條件不應該是x.contains(key)

+0

等什麼必須的條件? –

+0

import java.util。*; 公共類Corpuz_Kervin { \t公共靜態無效的主要(字串[] args) \t { \t \t掃描儀輸入=新掃描儀(System.in); \t \t String phrase,key; \t \t String plus =「+」; \t \t \t \t \t 是System.out.print \t( 「輸入主短語:」); \t \t phrase = input.next(); \t \t System.out.print(「Enter key string:」); \t \t key = input.next(); \t \t對(INT I = 0; I