2010-07-28 47 views
2

我的Android程序中有一個很長的字符串。 我需要的是,我需要分割該字符串的每個單詞,並將每個單詞複製到一個新的字符串數組。 對於例如:如果字符串是「我做機器人程序」和字符串數組爲my_array命名然後各指標中應包含的值:Android String Array Manipulation

my_array[0] = I 
my_array[1] = did 
my_array[2] = Android 
my_array[3] = Program 

程序的一部分,我做了如下所示:

StringTokenizer st = new StringTokenizer(result,"|"); 
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show(); 
while(st.hasMoreTokens()) 
{ 
String n = (String)st.nextToken(); 
services1[i] = n; 
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show(); 
} 

任何一個可以請提出一些想法..

+1

StringTokenizer在Java 6上已被棄用。 – 2010-07-28 13:06:09

回答

9

爲什麼不使用String.split()

你可以簡單地做

String[] my_array = myStr.split("\\s+"); 
0

您可以使用String.split或Android的TextUtils.split,如果你需要返回[]時,分割字符串是空的。

StringTokenizer API文檔:

的StringTokenizer是一個遺留類 保持兼容性的原因 雖然它的使用是在新 代碼氣餒。建議任何尋求此功能的 都使用String的 拆分方法或代替使用java.util.regex包的 。

1

由於'|'是正則表達式中的一個特殊字符,我們需要逃避它。

for(String token : result.split("\\|")) 
     { 
      Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show(); 
     } 
0

由於String是一個final類,它是默認不可改變的,這意味着你不能更改您的字符串。如果嘗試,將會創建一個新對象,而不是修改相同的對象。因此,如果您事先知道您將需要操作String,那麼從StringBuilder類開始是明智的。處理線程也有StringBuffer。在StringBuilder有喜歡substring()方法:

substring(int start) 
Returns a new String that contains a subsequence of characters currently contained in this character sequence. 

getChars()

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 
Characters are copied from this sequence into the destination character array dst. 

delete()

delete(int start, int end) 
Removes the characters in a substring of this sequence. 

然後如果你真的需要它進行到底,用一個String String構造函數

String(StringBuilder builder) 
Allocates a new string that contains the sequence of characters currently contained in the string builder argument. 

String(StringBuffer buffer) 
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument. 

雖然瞭解何時使用String方法以及何時使用StringBuilderthis linkthis可能的幫助。 (StringBuilder可以節省內存)。