Split Java String into Two String using delimiter

后端 未结 7 1084
情话喂你
情话喂你 2020-12-03 18:09

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 str

相关标签:
7条回答
  • 2020-12-03 18:21

    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 讨论(0)
  • 2020-12-03 18:22

    The split function is suitable for that :

    String[] str_array = "name:score".split(":");
    String stringa = str_array[0]; 
    String stringb = str_array[1];
    
    0 讨论(0)
  • 2020-12-03 18:29

    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];
    
    0 讨论(0)
  • 2020-12-03 18:34
    String row = "name:12345";
    String[] columns = row.split(":");
    assert columns.length == 2;
    String name = columns[0];
    int score = Integer.parseInt(columns[1]);
    
    0 讨论(0)
  • 2020-12-03 18:35

    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.

    0 讨论(0)
  • 2020-12-03 18:35

    $ 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
    
    0 讨论(0)
提交回复
热议问题