如何子字符串化

Dem*_*mer 4 java android substring

我想得到这个字符串的4个部分

String string = "10 trillion 896 billion 45 million 56873";
Run Code Online (Sandbox Code Playgroud)

我需要的4个部分是“ 10万亿”,“ 8960亿”,“ 4500万”和“ 56873”。

我要做的是删除所有空格,然后对其进行子字符串化,但是我对索引感到困惑。我看到了很多问题,但无法理解我的问题。

Sorry I don't have any code
Run Code Online (Sandbox Code Playgroud)

我不能跑步,因为我不知道那是对的。

Pri*_*nce 6

这是轻松获得解决方案的方法。

String filename = "10 trillion 896 billion 45 million 56873";
String regex = " [0-9]";

String[] parts = filename.split(regex);
String part1 = parts[0]; // 10 trillion
String part2 = parts[1]; // 896 billion
String part3 = parts[2]; // 45 million
String part4 = parts[3]; // 56873
Run Code Online (Sandbox Code Playgroud)

您也可以使用foreach循环获取值。

for(String str: parts){
    Log.i(TAG, "onCreate: parts : "+str);
}
Run Code Online (Sandbox Code Playgroud)


Swe*_*per 5

您可以使用此正则表达式:

\d+(?: (?:tri|bi|mi)llion)?
Run Code Online (Sandbox Code Playgroud)

它首先匹配一串数字\d+,然后可选地(?:...)?,我们匹配兆,十亿或百万(?:tri|bi|mi)llion

在此处输入图片说明

要使用此正则表达式,

Matcher m = Pattern.compile("\\d+(?: (?:tri|bi|mi)llion)?").matcher(string);
while (m.find()) {
    System.out.println(m.group());
}
Run Code Online (Sandbox Code Playgroud)


kar*_*ran 2

下面的代码将起作用。检查评论以获取添加的说明。

String input = "10 trillion 896 billion 45 million 56873";
        String pattern = "\\s\\d";     // this will match space and number thus will give you start of each number.
        ArrayList<Integer> inds = new ArrayList<Integer>();
        ArrayList<String> strs = new ArrayList<String>();
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(input);
        while (m.find()) {
            inds.add(m.start());          //start will return starting index.
        }

        //iterate over start indexes and each entry in inds array list will be the end index of substring. 
        //start index will be 0 and for subsequent iterations it will be end index + 1th position.
        int indx = 0;
        for(int i=0; i <= inds.size(); i++) {
            if(i < inds.size()) {
                strs.add(input.substring(indx, inds.get(i)));    
                indx = inds.get(i)+1;
            } else {
                strs.add(input.substring(indx, input.length()));
            }
        }

        for(int i =0; i < strs.size(); i++) {
            System.out.println(strs.get(i));
        }
Run Code Online (Sandbox Code Playgroud)