2

I have a String which is a website URL, such as "http://www.abcd.com/en/sites/default/files/pic.jpg". I want to split this String so that I can change some of the path values, such as changing /files/ to /newfolder/.

Is this easily achievable?

8 Answers 8

3
String[] afterSplit = yourString.split("files/");
String newString = afterSplit[0];
newString += "/newfolder/";
newString += afterSplit[1];

With a standard String.split() method, since you asked for splitting. newString is the resulting string.

Sign up to request clarification or add additional context in comments.

Comments

2

This will remove the part after the last "/" and append "newfolder/pic.jpg"

String str = "http://www.abcd.com/en/sites/default/files/pic.jpg";
str.substring(0, s.lastIndexOf("/") + 1) + "newfolder/pic.jpg";

1 Comment

In my opinion this is the best (most flexible) possibility (or even more general str.substring(0, s.lastIndexOf("/") + 1) + "newfolder" + substring(s.lastIndexOf("/"));)
1

Use a replace function and replace "files/" by "files/newfolder/", for example.

3 Comments

Yh..i get it..Thanks for your help :)
The solution with replace fails if the path before 'files' also contains 'files', for example in http://www.abcd.com/en/sites/files/default/files/pic.jpg
Good objection, but maybe not relevant in his setup.
1

How about:

String parts[] = String.split(oldPath, "files\");
String newPath = parts[0] + "newfolder\" + parts[1];

I haven't tested it but in theory it should work. There could be a problem with the backslash in the regular expression, but if so, its easy to fix.

Regards,

-Harry

Comments

0
string.replace("pic.jp" ,"newfolder/pic.jpg");

hope it helps

Comments

0
String string = "http://www.abcd.com/en/sites/default/files/pic.jpg";
string.replace("files/", "files/newfolder/");

1 Comment

wow!..look like the simplest method...Thanks Chandra Sekhar...let me check it out :)
0

This works:

String input = "http://www.abcd.com/en/sites/default/files/pic.jpg";
int lastIndexOfSlash = input.lastIndexOf('/');
String result = input.substring(0, lastIndexOfSlash + 1) + "newfolder/" + input.substring(lastIndexOfSlash + 1);

Comments

0

this should work:

String s = "http://www.abcd.com/en/sites/default/files/pic.jpg";
StringBuilder sb = new StringBuilder(s);
sb.insert(sb.lastIndexOf("/"), "/newfolder");
s = sb.toString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.