Arhana
Arhana

Reputation: 41

To separate substring from string

I have this string in java variable as

String t = "C:/clearpath/rafa.jpg";

Now I want to remove clearpath from variable t and want to store in other variable as

String j = "C://rafa.jpg".

How am i supposed to do this?

Upvotes: 1

Views: 55

Answers (3)

SriAji
SriAji

Reputation: 101

This works for that string.

String t = "C:/clearpath/rafa.jpg";
t = t.substring(0, 3) + t.substring(12, t.length());

Upvotes: 0

Swapnil Patil
Swapnil Patil

Reputation: 613

You can make use of java.nio.file.Path. By using Path you can manipulate your path in many ways.

In your case, you can get the file name by

Path path = Paths.get("C:/clearpath/rafa.jpg");
Path fileNm = path.getFileName();

& file root as

Path fileRoot = path.getRoot();

At the end, simply concatenate them together.

System.out.println(fileRoot.toString() + fileNm.toString());

The final output will be like

C:\rafa.jpg

Upvotes: 0

dan1st
dan1st

Reputation: 16338

You can do this with

t=t.replace("clearpath","");

Upvotes: 2

Related Questions