当前位置: 代码迷 >> J2EE >> java String 字符串截取,该如何解决
  详细解决方案

java String 字符串截取,该如何解决

热度:187   发布时间:2016-04-22 01:32:26.0
java String 字符串截取
String color = "";
String size = "";
String values = "Lady Size:M.Select Color:As the Picture";
size = "Lady Size:M.Select";
color = "Color:As the Picture";


如何截取

------解决方案--------------------
用indexOf和substring
------解决方案--------------------
[code=Java][/code]public class TestIndex {
String color = "";
String size = "";
public static String values = "Lady Size:M.Select Color:As the Picture";
public static void main(String[] args){
splitString();
}
public static void splitString(){
int index=values.indexOf("Color");
System.out.println(values.subSequence(0, index));
System.out.println(values.subSequence(index,values.length() ));
}
}
------解决方案--------------------
一般字符串的截取都是用到用indexOf和substring两个方法。。看看API。。String类中的方法。 。应该就可以搞定
------解决方案--------------------
[code=Java]
public static void main(String args[]) {
String color = "";
String size = "";
String values = "Lady Size:M.Select Color:As the Picture";

int position = getPosition(values," ",2);

color = values.substring(0, position);
size = values.substring(position);

System.out.println(position);
System.out.println("color = " + color );
System.out.println("size = " + size);

}

public static int getPosition(String aimStr, String substr, int sequent) {

if (sequent < 0)
return 0;
String[] tmpArray = aimStr.split(substr);
if (sequent > tmpArray.length)
return -1;
String tmp = tmpArray[sequent] + substr;
return aimStr.indexOf(tmp);

}
[/code
写个小函数
------解决方案--------------------
Java code
String color = "";String size = "";String values = "Lady Size:M.Select Color:As the Picture";size = "Lady Size:M.Select";color = "Color:As the Picture";String[] strs = values.split("\\s+(?=Color)");size = strs[0];color = strs[1];
  相关解决方案