开发者

how to split the string in java

how to split the string in java in Windows? I used Eg.

String directory="C:\home\public\folder";
String [] dir=direct.split("\");

开发者_如何学GoI want to know how to split the string in eg. In java, if I use "split("\")" , there is syntax error.

thanks


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.


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


You need to escape the backslash:

direct.split("\\\\");

Once for a java string and once for the regex.


You need to escape it.

String [] dir=direct.split("\\\\");

Edit: or Use Pattern.quote method.

 String [] dir=direct.split(Pattern.quote("\\"))


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());
}


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.


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);


It's because of the backslash. A backslash is used to escape characters. Use

split("\\")

to split by a backslash.


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


split("\\") A backlash is used to escape.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜