简体   繁体   中英

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("\");

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

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.

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

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

split("\\")

to split by a backslash.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM