I have a string "domain\cdsid"
, where "\"
is the delimiter, all I want is to split the string and just print "cdsid"
.
Input string : "domain\cdsid"
Output string : "cdsid"
How do I do this ?
I have a string "domain\cdsid"
, where "\"
is the delimiter, all I want is to split the string and just print "cdsid"
.
Input string : "domain\cdsid"
Output string : "cdsid"
How do I do this ?
Try this (using split
) :
String myText = "domain\\cdsid";
System.out.println(myText.split("\\\\")[1]);
Output :
cdsid
In Java String object "\" is used to define any escape sequence character like \n for new line, \t for tab, \\ for having a backslash in the String object.
So instead of writing String object as
String str = "domain\cdsid";
You have to write
String str = "domain\\cdsid";
The first option will give compile time error. Java will expect that after backslash their must be some escape sequence character but it is not their in first case. It will compile time error as
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
In the above compile time error each separate value is a escape sequence character in java.
So your final code will be
String str = "domain\\cdsid";
System.out.println(str.split("\\\\")[1]);
Hope this helps.
Splitting is a way that I will recommended to go when you need all the elements resulting of the operation... this is because the result will generate an Array of Strings (what a waste of memory generating an array to only get ONE element! :) dont you think??)
in your case something like regex or just substrings will gently provide you the correct answer..
consider:
String txt = "domain\\cdsid";
System.out.println(txt.substring(txt.indexOf("\\") + 1));
output:
cdsid