Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add number of character Occurrences inside a string

My task is to find number of occurrences of a string character and add that number inside the string

public static void main(String[] args) {

    char[] arr = "hello".toCharArray();
    
    arr[2] = '1';
    arr[3] = '2';
    
    System.out.println(arr);
}

Output should be: he12o

I know we cant reuse this approach.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

what is the output of "helololol"?

output for helololol, ch=’l’ , then the output should be he1o2o3o4; if ch=’o’ then output should be hel1l2l3l

If according to this rule, Can be achieved with a loop:

public static void main(String[] args) {
    char flag = 'l';
    String str = "hellollololollol";
    int num = 1;
    for(int i = 0, len = str.length(); i < len; i++) {
        if (str.charAt(i) == flag) {
            str = str.substring(0, i) + num++ + str.substring(i + 1);
        }
    }
    System.out.println(str);
}

Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:

public static void main(String[] args) {
    char flag = 'l';
    String str = "hellollololollollol";
    int num = 1;
    for(int i = 0, len = str.length(); i < len; i++) {
        if (str.charAt(i) == flag) {
            str = str.substring(0, i) + num++ + str.substring(i + 1);
            if (num > 10) {
                len++;
            }
        }
        System.out.println(str);
    }
}

The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading