简体   繁体   中英

Converting string with letters and numbers

So I have a String declared as String name = "John 20150.00" and I want to break up the name into a different variable and the number into a different variable, is this possible?

I tried using the Double.parseDouble(name); method, but when it runs, it doesn't work right.

What should I use?

You can use java.util.Scanner to break apart your string and parse the results

Scanner s = new Scanner(name);
String firstName = s.next();
double number = s.nextDouble();

You can also take advantage of methods such as .hasNextDouble() to test if the next token (the default separator between tokens is white-space) is actually parseable into a double. The Scanner class also provides for the flexibility of regular expressions to define your token delimiters, making it very powerful.

First you will need to split the string:

String[] parts = name.split(" ");

Here we splitted on the space.

Then we obtain each part by:

String firstName = parts[0];
double cash = Double.parseDouble(parts[1]);

That should work.

you should separate the string into two parts: letters part and numbers part. Use indexOf(' ') to find the index of the whitespace that separate the name and the letter. Then create two strings, one for letters and one for numbers using substring(). For details you can check the java api about how to use all these methods.

An example

String str = "Hi 4.5";
int index = str.indexOf(' ');
String letters = str.substring(0, index);
String numbers = str.substring(index + 1);
double numbersDouble = Double.parseDouble(numbers);
System.out.println(numbersDouble);

You can strip out non-number characters using regex before parsing:

double d = Double.parseDouble(name.replaceAll("[^\\d.]", ""));

After extracting the number, you can extract the name similarly:

name = name.replaceAll("[\\d.]","").trim();

This approach of using regex has the advantage that it doesn't matter if the number comes first or last in the string - it will still work. It also works if there are spaces in the name, eg "Billy Bob 123.45"

There are a few ways you might achieve this and the method you choose will come down to your overall requirements

You Could...

Simply use String#split , for example...

String value = "John 20150.00";
String[] parts = value.split(" ");
for (String part : parts) {
    System.out.println(part);
}

This allows you to break a String apart on a known token (which could be a regular expression itself)

You Could...

Use a regular expression...

String regExp = "([A-Za-z]+)|([0-9]+(.[0-9]+))";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Which would allow you to match on a more complex set of rules. Matcher includes groupCount and getGroup methods, so you can access the elements individually.

This would allow you to handle cases where a split token might appear within a capture group, for example John Walker 20150.00 , which you might be able to use ([A-Za-z]+([ ][A-Za-z]+))|([0-9]+(.[0-9]+)) to capture Jonh Walker and 2015.00 separately.

You can't (easily) use split ...you could, but it just gets more complex, especially if the String contained other names and amounts, for example...

nb: I should point out, my regular expression is pretty basic, so there might be better expressions that are more flexible and neat better results...

Why just not:

String[] cake = name.split(" ")
String a = cake[0]
double b = Double.parseDouble(cake[1])

First you want to separate the string and double

StringTokenizer st = new StringTokenizer(name);
Sting personsName = st.nextToken();
double d = Double.parseDouble(personName);

that is what you need to do. The error was because you tried to convert a string object to a number, but it had letters not digits only.

Something like this maybe:

String name = "John 20150.00";
String[] parts = name.split(" ");
String person = parts[0];
Double value = new Double(parts[1]);

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