Reputation: 1525
how to split the string in java in Windows? I used Eg.
String directory="C:\home\public\folder";
String [] dir=direct.split("\");
I want to know how to split the string in eg.
In java, if I use "split("\")"
, there is syntax error.
thanks
Upvotes: 2
Views: 20692
Reputation: 41
String[] a1 = "abc bcd"
String[] seperate = a1.split(" ");
String finalValue = seperate[0];
System.out.pritln("Final string is :" + finalValue);
This will give the result as abc
Upvotes: -1
Reputation: 25
final String dir = System.getProperty("user.dir");
String[] array = dir.split("[\\\\/]",-1) ;
String arrval="";
for (int i=0 ;i<array.length;i++)
{
arrval=arrval+array[i];
}
System.out.println(arrval);
Upvotes: 0
Reputation: 2346
Please, don't split using file separators.
It's highly recommended that you get the file directory and iterate over and over the parents to get the paths. It will work everytime regardless of the operating system you are working with.
Try this:
String yourDir = "C:\\home\\public\\folder";
File f = new File(yourDir);
System.out.println(f.getAbsolutePath());
while ((f = f.getParentFile()) != null) {
System.out.println(f.getAbsolutePath());
}
Upvotes: 2
Reputation: 49
I guess u can use the StringTokenizer library
String directory="C:\home\public\folder";
String [] dir=direct.split("\");
StringTokenizer token = new StringTokenizer(directory, '\');
while(token.hasTokens()
{
String s = token.next();
}
This may not be completely correct syntactically but Hopefully this will help.
Upvotes: 0
Reputation: 30865
The syntax error is caused because the sing backslash is used as escape character in Java.
In the Regex '\'
is also a escape character that why you need escape from it either.
As the final result should look like this "\\\\"
.
But You should use the java.io.File.separator
as the split character in a path.
String[] dirs = dircect.split(Pattern.quote(File.separator));
thx to John
Upvotes: 7
Reputation: 63688
You need to escape it.
String [] dir=direct.split("\\\\");
Edit: or Use Pattern.quote method.
String [] dir=direct.split(Pattern.quote("\\"))
Upvotes: 3
Reputation: 8004
split()
function in Java accepts regular expressions. So, what you exactly need to do is to escape the backslash character twice:
String[] dir=direct.split("\\\\");
One for Java, and one for regular expressions.
Upvotes: 13
Reputation: 8550
You need to escape the backslash:
direct.split("\\\\");
Once for a java string and once for the regex.
Upvotes: 5
Reputation: 75578
It's because of the backslash. A backslash is used to escape characters. Use
split("\\")
to split by a backslash.
Upvotes: -1