Rohit
Rohit

Reputation: 65

Remove domain name from string java

I have a string which looks like this

String str = "domain\ABC";
String str = "domain1\DEF";

How do i write a common function to remove the "domain\" or "domain1\" and just have the string after the the '\'. I tried a couple of different ways but none seem to work.

This is what i have tried.

String[] str = remoteUser.split(remoteUser, '\\');

Upvotes: 1

Views: 2450

Answers (4)

Dorian Gray
Dorian Gray

Reputation: 2981

Try this:

static String getPath(String url) {
    int pos = url.indexOf('\');
    return pos >= 0 ? url.substring(pos + 1) : url;
}

Upvotes: 0

Andreas
Andreas

Reputation: 159127

No need for split() or regex for this, as that is overkill. It's a simple indexOf() operation.

How do i write a common function ... ?

Like this:

public static String removeDomain(String input) {
    return input.substring(input.indexOf('/') + 1);
}

The code relies on the fact indexOf() returns -1 if / is not found, so the + 1 will make that 0 and substring(0) then returns input string as-is.

Upvotes: 6

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

You might use replaceAll:

 System.out.println("domain\\ABC".replaceAll("^.*\\\\",""));

It will replace everything starting at the beginning of the string, until \ symbol.

Upvotes: 0

Ran_Macavity
Ran_Macavity

Reputation: 154

Try it like this.

String str = "domain\\ABC";
String[] split = str.split("\\\\");

//Assign the second element of the array. This only works if you know for sure that there is only one \ in the string.
String withoutSlash = split[1];

Hope it helps.

Upvotes: 1

Related Questions