2010-07-28 94 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可以节省内存)。