User7723337
User7723337

Reputation: 12018

Subtracting string from a string [Android]

I have following two string:

String one:
"abcabc/xyzxyz/12345/random_num_09/somthing_random.txt"

String Two:
"abcabc/xyzxyz/12345/"

What i want to do is attach path "random_num_09/somthing_random.txt" from string one two string two. So how can i subtract string two from string one and then attach remaining part to string two.

I have tried to do it by searching for the second last "/" in the string one and then doing sub string and attaching it to string two.

But is there any better way of doing it.

Thanks.

Upvotes: 0

Views: 2152

Answers (2)

verybadalloc
verybadalloc

Reputation: 5798

I think the best way is to use substrings, as you said:

String string_one = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string_two = "abcabc/xyzxyz/12345/";
String result = string_two + string_one.substring(string_one.indexOf(string_two)+1));

The other possibility is to use regex, but you would still be doing concatenation to get the result.

Pattern p = Pattern.compile(string_two+"(.*)");
Matcher m = p.matcher(string_one);
if (m.matches()) {
  String result = string_two+m.group(1);
}

Upvotes: 2

njzk2
njzk2

Reputation: 39397

rather that a substring, replace is simpler to use:

String string1 = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string2 = "abcabc/xyzxyz/12345/";
String res = string2 + string1.replace(string2, "");

Upvotes: 2

Related Questions