有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java基于前导词增加字符串中的数字

我有很大的文本文件,每个文件都包含字符串和数字。 我需要将这些数字增加一个固定的值,然后将它们写回到字符串中之前的位置

我想添加的值取决于数字前面的单词,每个没有这些关键字的数字都必须增加

我的方法是在空格处拆分字符,检查单词并在找到关键字后处理数字。然而,这给我留下了在单词和数字之间使用空格字符的要求,这是无法保证的

此外,当从拆分数组重新组装字符串时,这可能会打破以前的布局

例如: “马克相当大,189厘米,出生于1978年。然而,他只有一个关于解析的问题,他真的不能动脑。”

在大的之后,高度应该增加5,在一年之后,这个数字减去19。数字1应该保持不变,因为only不是关键字

我可以同时使用java或python,因为这是我所知道的语言


共 (1) 个答案

  1. # 1 楼答案

    我想我得到了一些东西:

    public class Start {
        public static void main(String[] args){
            //Test String
            String s = "not4inc6desc3inc14";
    
            StringBuffer sb = new StringBuffer(s);
    
            //keep track where new word begins
            int newWord = 0;
    
            for(int i = 0; i < sb.length(); i++){
    
                //chekc if the new Character is a number
                if(checkNumber(sb.substring(i, i+1))){
    
                    //if the old word ends with "inc"
                    //maybe try out .contains()
                    if(sb.substring(newWord, i).endsWith("inc")){
                        //replace number
                        StringBuffer temp = new StringBuffer();
                        int j  = 0;
    
                        //get full number
                        for(j = i; j < sb.length() && checkNumber(sb.substring(j, j+1)); j++){
                            temp.append(sb.substring(j, j+1));
                        }
    
                        //modify number
                        int number = Integer.parseInt(temp.toString()) + 1;
    
                        //replace number
                        sb.replace(i, i + temp.length(), Integer.toString(number));
    
                        //number no longer needs to be checked for being a word
                        i=j;
                    }
                }
            }
    
            //print test String
            System.out.println(sb.toString());
    
        }
    
        // Check if String is numeric
        private static boolean checkNumber(String s){
            try{
                Integer.parseInt(s);
            }catch(NumberFormatException e ){
                return false;
            }
            return true;
        }
    }
    

    很抱歉这有点难理解。。。请随便问