Home > Enterprise >  How to add number of character Occurrences inside a string
How to add number of character Occurrences inside a string

Time:01-30

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.

CodePudding user response:

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!

CodePudding user response:

Instead of using primitive methods to manipulate string , we can use the following to have clean code .

public static void main(String args[]) {
        String str="helolololololololololololololololololololololololololololololololololololo";
        String checkString="l";
        int count=1;
        StringBuilder sb=new StringBuilder();
        List<String> strLst= new ArrayList<String>();
        for(int i=0;i<str.length();i  ) {
            strLst.add(String.valueOf(str.charAt(i)));
        }
        
        for(String x : strLst) {
            if(x.equals(checkString)) {
                sb.append(count);
                count  ;
            }else {
                sb.append(x);
            }
        }
        System.out.println(sb);
    }

The output for the above string will be he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o

With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.

  • Related