how to split the string in java

后端 未结 10 1684
梦如初夏
梦如初夏 2020-12-11 10:44

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

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


        
相关标签:
10条回答
  • 2020-12-11 11:11

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

    0 讨论(0)
  • 2020-12-11 11:14

    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.

    0 讨论(0)
  • 2020-12-11 11:14

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

    split("\\")
    

    to split by a backslash.

    0 讨论(0)
  • 2020-12-11 11:16

    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

    0 讨论(0)
  • 2020-12-11 11:23

    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());
    }
    
    0 讨论(0)
  • 2020-12-11 11:26
    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);
    
    0 讨论(0)
提交回复
热议问题