2013-10-12 32 views
-1
public static void main(String[] args){ 
Scanner scan = new Scanner(System.in); 
String read = scan.readLine(); 
String str = read + ":" + "world"; 
String[] sets = str.split(":"); 
System.out.println(sets[0] + sets[1]); 
} 

在這裏,如果我們輸入hello,我會得到hello world。但是,當用戶輸入具有「:」的數據時,輸入的字符串也會被分割,並且不會打印「:」。不能拆分包含「:」的輸入數據可以做些什麼?用戶輸入數據的字符串分割問題

+2

你**的指令模式拆分**。 –

回答

2

不要劈在相同的字符,用戶可以輸入自己。

即使它可能太多,你可以確定它不會再發生使用uuid作爲分隔符。

Scanner scan = new Scanner(System.in); 
String read = scan.readLine(); 
String separator = UUID.randomUUID().toString(); 
String str = read + separator + "world"; 
String[] sets = str.split(separator); 
System.out.println(sets[0] + sets[1]); 
+0

您應該測試用戶數據是否不包含隨機分隔符,並且如果它確實再次進行了隨機分配,直到它沒有。我不確定uuid是否可以有一些正則表達式元字符,因此如果它可以分割應該在'Pattern.quote(separator)'上完成。 – Pshemo

+0

'UUID'字符串表示只包含'[0-9a-f-]',32個字符(36包括'-'),用戶可能會意外地鍵入和匹配它,這對我來說似乎幾乎不可能,但是對於您可以檢查它,只是爲了**真的**肯定這一次:-)。 – Alex

+0

@Pshemo我們如何使用'Patten.quote(separator)'做到這一點? – Mercenary

-1

從文檔:

public String[] split(String regex) 

Splits this string around matches of the given regular expression. 

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. 
-1
str.split(/*regex*/); 

去除提供給從所提供的串分裂()的定界符/正則表達式並返回一個字符串數組。這就是爲什麼你不從split()

Link to DOCS

+0

我知道字符串分割是如何工作的。我正在尋找解決上述問題的方法! – Mercenary

0

明顯而簡單的解決方案看到返回的字符串數組中::如果有可能改變你的分隔符。您還可以使用管道(|),#,$,還有更多!只要找到一個你確定它不會出現在輸入中!如果您使用正則表達式,您甚至可以嘗試使用分隔符組合!

如果您的分隔符是:; (隨後由冒號分號)可以拆分這樣的使用正則表達式:

str.split("[:]{1}[;]{1}"); 

它的意思後緊跟一個分號一個冒號!

希望這有助於:)。

0

嘗試這樣如下:

char[] delims = {':'}; 
     for (char delim : delims) { 
     for (int i = 0; i < read.length(); i++) { 
      if (read.charAt(i) == delim) { 
       //Now write your code here 
    String str = read + "world"; 
      } 
else 
{ 
String str = read + ":" + "world"; 
} 
     } 
     }