Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substring this String

I want to get 4 parts of this string

String string = "10 trillion 896 billion 45 million 56873";

The 4 parts I need are "10 trillion" "896 billion" "45 million" and "56873".

What I did was to remove all spaces and then substring it, but I get confused about the indexes. I saw many questions but could not understand my problem.

Sorry I don't have any code

I couldn't run because I didn't know that was right.

like image 734
Demon App Programmer Avatar asked Jun 07 '19 05:06

Demon App Programmer


2 Answers

This is a way to get your solution easily.

String filename = "10 trillion 896 billion 45 million 56873";
String regex = " [0-9]";
    
String[] values = filename.split(regex);
// You can get the value by position -> values[0] ... values[n]

// Use the Foreach loop to get all the values.
for(String subValue: values ){
    Log.i(TAG, "Part : "+subValue);
}
like image 76
Prince Dholakiya Avatar answered Sep 22 '22 08:09

Prince Dholakiya


You can use this regex:

\d+(?: (?:tri|bi|mi)llion)?

It first matches a bunch of digits \d+, and then optionally (?:...)?, we match either trillion, billion, or million (?:tri|bi|mi)llion.

enter image description here

To use this regex,

Matcher m = Pattern.compile("\\d+(?: (?:tri|bi|mi)llion)?").matcher(string);
while (m.find()) {
    System.out.println(m.group());
}
like image 41
Sweeper Avatar answered Sep 26 '22 08:09

Sweeper