简体   繁体   中英

Splitting a string that has numbers and characters into an int and String

I have a String that goes "Peyton Manning; 49". Is there a way to have the computer read the left side of the String and make it equal to a new String "Peyton Manning" and take the right side of the String and make it equal to an int with a value of 49?

A number of ways spring to mind: you can tokenize or you can use regexs. You didn't specify about white space padding. Also, you didn't specify if the string segments around the delimiter can be invalid integers, mixtures strings digits etc. If this helped you, please mark accordingly.

    public class Test {
        public static void main(String[] args) {
        String s="Blah; 99";

        StringTokenizer st = new StringTokenizer(s, ";");
        String name = st.nextToken();
        Integer number = Integer.parseInt(st.nextToken().trim());
        System.out.println(name.trim() + "---" + number);

        number = Integer.parseInt(s.replaceAll("[^0-9]", ""));
        name = s.replaceAll("[^A-Za-z]", "");
        System.out.println(name + "---" + number);

        int split = s.indexOf(";");
        name = s.substring(0, split);
        number = Integer.parseInt(s.substring(split+2, s.length()));
        System.out.println(name + "---" + number);
    }
}

The simplest way is:

String text = input.replaceAll(" *\\d*", "");
int number = Integer.parseInt(input.replaceAll("\\D", ""));

See KISS principle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM