2016-09-27 44 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