M Karimi
M Karimi

Reputation: 3513

How to split a string in Android according to a given condition?

I have a string, 12-512-2-15-487-9-98 and I want to split into two strings such below:

str1="12-512-2";
str2="15-487-9-98";

That means the first string will contain the characters before third -, and the second string will contain the remaining characters after that.

How can I do this? I tried that by using split("-") and concat str[0]+"-"+str[1]+"-"+str[2] but I want easier answer.

Upvotes: 0

Views: 393

Answers (4)

hungr
hungr

Reputation: 2096

I guess using regex seems easier?

String line = "12-512-2-15-487-9-98";
String pattern = "(\\d+-\\d+-\\d+)-(\\d+-\\d+-\\d+-\\d+)";


Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

if (m.find( )) {
  System.out.println("Found value: " + m.group(0) );
  System.out.println("Found value: " + m.group(1) );
  System.out.println("Found value: " + m.group(2) );
} else {
  System.out.println("NO MATCH");
}

The value of m.group(1) and m.group(2) are what you want.

Another way is using StringUtils.ordinalIndexOf in Apache Commons Lang library to find the index of the 3rd occurrence of - and call substring with the index obtained.

Upvotes: 1

Dor
Dor

Reputation: 657

the idea is to iterate the string and increase the counter when you see "-"
at the 3rd "-" it will split the string by using substring and provide the index you found the 3rd "-" at.

It might need a little adjustment to the index if it isn't splitting it as it should.

it should look like this:

     String temp = "12-345-678-44-55-66-77";
    int counter = 0;
    String string1 = "";
    String string2 = "";

    for(int i = 0 ; i<temp.length()-1;i++){
        if(temp.charAt(i) == '-'){
            counter++;
        }
        if(counter == 3){
            string1 = temp.substring(0,i-1);
            string2 = temp.substring(i+1,temp.length()-1);
            System.out.println(string1+" "+string2);
        }
    }

Upvotes: 0

Nisarg Doshi
Nisarg Doshi

Reputation: 13

You can get it by str.indexOf() function where you need to pass character and starting index of your string

For your example

int indexofSecondOccurance=str.indexOf("-", str.indexOf("-") + 1);  
int finalIndex = str.indexOf("-", indexofSecondOccurance + 1));

After that, you can split your string by substring().

Upvotes: 0

Jakir Hossain
Jakir Hossain

Reputation: 3930

Try like this

String text = "12-512-2-15-487-9-98";
int pos = text.indexOf('-', 1 + text.indexOf('-', 1 + text.indexOf('-')));
String first = text.substring(0, pos);
String second = text.substring(pos+1);

System.out.println(first); // 12-512-2
System.out.println(second); // 15-487-9-98

Upvotes: 1

Related Questions