您的位置:首页 > 编程语言 > Java开发

java解析字符串拆分单独元素

2016-03-08 18:05 507 查看
有时候,需求要求传递多个字符串参数,但是方法参数已经固定为单个String,笔者在学习unity和android之间的消息传递时就遇到这个问题,所以就写了这么一个解析字符串拆分单独元素的方法。

[b]示例:“@my@red@apple”[/b]

[b]解析为:[/b]

[b]my[/b]

[b]red[/b]

[b]apple[/b]

package cutstring;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* @ClassName: MainClass
* @Description: 字符串格式"@a@b@c",a,b,c会被解析为单独的元素
* @author luxishi
* @date 2016年3月8日 下午5:57:56
*
*/
public class MainClass {

public static void main(String[] args) {
String m_sentence="@my@red@apple";
List<String> m_list=cutstring(m_sentence);
System.out.println(m_list.size());
for(String tmp:m_list){
System.out.println(tmp);
}

}

static List<String> cutstring(String Stence)
{
List<String> stringlist=new ArrayList<String>();//用来存储解析出来的元素
for(int i=0;i<Stence.length();i++)
{
if(Stence.charAt(i)=='@')
{
String temp="";//存储单词
int wordlength=i;
while(wordlength<Stence.length()-1&&Stence.charAt(++wordlength)!='@')
{
temp+=Stence.charAt(wordlength);
//System.out.println(temp);
}
stringlist.add(temp);
}
}
return stringlist;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: