-4

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 ?

Jarvis
  • 8,494
  • 3
  • 27
  • 58
Irthiza Khan
  • 23
  • 1
  • 7

3 Answers3

1

Try this (using split) :

String myText = "domain\\cdsid";
System.out.println(myText.split("\\\\")[1]);

Output :

cdsid
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • That looks fine, but if you see this here. "String[] loginname= (node.getAttributes().getNamedItem("LoginName").getNodeValue()).split("\\");" Iam extracting the data from sharepoint and its the "LoginName" which has this format "domain\cdsid" its predefined. – Irthiza Khan Nov 29 '16 at 13:12
  • You can't have a ``\`` inside a String, so, even if the method is returning the string `"domain\cdsid"`, it actually IS `"domain\\cdsid"`, and hence, the corresponding split. – Jarvis Nov 29 '16 at 13:17
  • Glad you got it. Please mark the answer as accepted. :) @IrthizaKhan – Jarvis Nov 30 '16 at 02:09
0

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.

SachinSarawgi
  • 2,632
  • 20
  • 28
-1

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

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97