Home > database >  How to populate with previous value in ; separated string?
How to populate with previous value in ; separated string?

Time:09-29

I have a semicolon (;) separated string like this: 11;21;12;22;13;;14;24;15;25.

Look one value is missing after 13. I Want to populate that missing number with 13(previous value) and store it into another string.

CodePudding user response:

Try this.

static final Pattern PAT = Pattern.compile("([^;] )(;; )");

public static void main(String[] args) {
    String input = "11;21;12;22;13;;;14;24;15;25";
    String output = PAT.matcher(input)
        .replaceAll(m -> (m.group(1)   ";").repeat(m.group(2).length()));
    System.out.println(output);
}

output:

11;21;12;22;13;13;13;14;24;15;25

CodePudding user response:

What have you tried so far?

You could solve this problem in many ways i think. If you like to use regular expression, you could do it that way: ([^;]*);; .

Or you could use a simple String.split(";"); and iterate over the resulting array. Every empty string indicates that there was this ;;

CodePudding user response:

This splits the string, looks for an empty array entry, replaces that, and the reassembles the string with semicolons and stores it in a new String object.

String[] stringArray = yourString.split(";");
for(int i = 0; i < stringArray.length(); i  ){
    if(stringArray[i] == ""){
        stringArray[i] = "13";
    }
}
StringBuilder sb = new StringBuilder();
for(int i = 1; i < stringArray.length(); i  ){
    if(i != 0){
        sb.append(";");
    }
    sb.append(stringArray[i]);
}
String result = sb.toString();
   

CodePudding user response:

        String str = "11;21;12;22;13;;14;24;15;25";
        String[] a = str.split(";");
        for(int i=0; i<a.length; i  ){
            if(a[i].length()==0){
                System.out.println(a[i-1]);
            }
        }
  • Related