Java 在正斜杠上拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24733222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:33:43  来源:igfitidea点击:

Split the string on forward slash

javastringsplit

提问by saurav

I have a code which I wanted to split based on the forward slash "/".

我有一个代码,我想根据正斜杠“/”进行拆分。

Whenever I have a regex split based on "////" it never splits and gives me the whole string back. I tried replacing with file separator which gives "\" and then splitting with "\\" works but not the below code.

每当我根据“////”进行正则表达式拆分时,它永远不会拆分并将整个字符串返回给我。我尝试用给出“\”的文件分隔符替换,然后用“\\”分割,但不是下面的代码。

Below is the code tested

下面是经过测试的代码

package org.saurav.simpletests.string;

import java.io.File;

public class StringManipulator {

    public static void main(String a[]){
        String testString ="/UserId/XCode/deep";

        //testString = testString.replace("/", File.separator);
        //testString = testString.replace("/", "_");
        testSplitStrings(testString);
    }

    /**
     * Test the split string
     * @param path
     */
    public static void testSplitStrings(String path){
        System.out.println("splitting of sprint starts \n");
        String[] paths = path.split("////");
        for (int i = 0; i < paths.length; i++) {
            System.out.println("paths::"+i+" "+paths[i]+"\n");
        }
        System.out.println("splitting of sprint ends");
    }
}

cheers, Saurav

干杯,索拉夫

回答by Keppil

There is no need to escape forward slashes. Your code works fine if you just do:

没有必要逃避正斜杠。如果您只是这样做,您的代码就可以正常工作:

String[] paths = path.split("/");

回答by Akky

String[] paths = path.split("\");

回答by IrvineCAGuy

Java might return a null pointer so you need to wrap this with a try catch

Java 可能会返回一个空指针,因此您需要使用 try catch 来包装它

try {
        String[] temp = imageFilenameOriginal.split("/");

    } catch (Exception ex){
        errorMessage = ex.getMessage();
    }

The compiler is much happier this way.

这样编译器会更快乐。

回答by shreshth

i wanted to check validation of input date in the format dd/mm/yyyyso need to split my string around /You can do it simply by:

我想以格式检查输入日期的验证,dd/mm/yyyy因此需要拆分我的字符串/您可以简单地通过以下方式完成:

String spl[]=str.split("/");
int date=Integer.parseInt(spl[0]);
int month=Integer.parseInt(spl[1]);
int year=Integer.parseInt(spl[2]);