如何子串这个字符串 [英] How to substring this String

查看:39
本文介绍了如何子串这个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get 4 parts of this string

String string = "10 trillion 896 billion 45 million 56873";

我需要的4个部分是10万亿"8960亿"4500万"和56873".

The 4 parts I need are "10 trillion" "896 billion" "45 million" and "56873".

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

What I did was to remove all spaces and then substring it, but I get confused about the indexes. I saw many questions but could not understand my problem.

Sorry I don't have any code

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

I couldn't run because I didn't know that was right.

推荐答案

下面的代码将起作用.查看评论以了解添加的说明.

Below code will work. Check comments for added instructions.

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

这篇关于如何子串这个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆