开发者

Split Java String into Two String using delimiter

开发者 https://www.devze.com 2023-04-13 04:36 出处:网络
I have a string that has the value of name:score. I want to split the 开发者_开发百科string into two strings, string a with the value of name and string b with the value of score.

I have a string that has the value of name:score. I want to split the 开发者_开发百科string into two strings, string a with the value of name and string b with the value of score.

What is the correct function/syntax to do this?

I have looked at string.split, but can not find the actual syntax to return the data into two separate strings.


The split function is suitable for that :

String[] str_array = "name:score".split(":");
String stringa = str_array[0]; 
String stringb = str_array[1];


You need to look into Regular Expressions:

String[] s = myString.split("\\:"); // escape the colon just in case as it has special meaning in a regex

Or you can also use a StringTokenizer.


Use:

String [] stringParts = myString.split(":");


String row = "name:12345";
String[] columns = row.split(":");
assert columns.length == 2;
String name = columns[0];
int score = Integer.parseInt(columns[1]);


Split creates an array with your strings in it:

String input = "name:score";
final String[] splitStringArray = input.split(":");
String a = splitStringArray[0];
String b = splitStringArray[1];


$ cat Split.java

public class Split {
    public static void main(String argv[]) {
        String s = "a:b";
        String res[] = s.split(":");
        System.out.println(res.length);
        for (int i = 0; i < res.length; i++)
            System.out.println(res[i]);
    }
}

$ java Split

2
a
b


what if you have something like this a:1:2 name = a:1??

 private String extractName(String str) {
    String[] split = str.split(":");
    return str.replace(split[split.length - 1], "");
  }

  private int extractId(String str){
    String[] split  = str.split(":");
    return  Integer.parseInt(CharMatcher.DIGIT.retainFrom(split[split.length-1]));
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号