Search code examples
javaarraysstringcounter

A series of String Manipulation Operations with counter in Java


Question:

The below string contains multiple words each separated by hash(#). After splitting each word by #,

  1. Reverse each character in words.
  2. Start the counter form 1 for each word.
  3. Find the character a,e,i,o,u and if you find the character then replace it with counter value and increment to 1.
  4. Reset the counter for each word.
  5. Print the final string. Print the string at the end. Example:

Input: my#name#is#manan Output: ym 1m2n s1 n1n2m

My Code is :

import java.lang.*;
import java.io.*;
import java.util.*;

class StrSplit {
    public static void main(String[] args) {
        String sentence = "my#name#is#manan";
        String[] word = sentence.split("#");
        String[] reverseword = new String[word.length];

        for (int i = 0; i < word.length; i++) {
            StringBuilder revword = new StringBuilder(word[i]);     // METHOD FOR USING .reverse()
            revword.reverse();      // REVERSING

            reverseword[i] = revword.toString();        // SAVING REVERSED WORDS INTO AN ARRAY.
        }

        for (int i = 0; i < reverseword.length; i++) {
            int counter = 1;
            String current = reverseword[i];        //SELECTING A WORD

            for (int j = 0; j < current.length(); j++) {
                char ch = current.charAt(j);        //SELECTING A CHARACTER 

                char count=(char)(counter+ '0');     //VOWEL COUNTER

                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    current = current.replace(current.charAt(j),count);     //REPLACE VOWEL WITH NUMBER
                    counter++; 
                }
            }           
            counter=1;   
            
            StringBuilder output= new StringBuilder(current);
            output.append(' ');
            System.out.print(output);
        }
    }
}

But there is one error in my output. My output is :

ym 1m2n s1 n1n1m 

While it should have been :

ym 1m2n s1 n1n2m 

The problem is, the counter is only incrementing if the vowels are not the same.


Solution

  • current.replace(current.charAt(j),count) replaces all the occurrences of current.charAt(j), so if the same vowel appears multiple times, you replace all of its occurrences in a single call, and increment the counter just once.

    You can replace just the first occurrence if you change

    current = current.replace(current.charAt(j),count); 
    

    to

    current = current.replaceFirst(current.substring(j,j+1),Integer.toString(counter));
    

    This way the counter will be incremented once for each replaced character.

    Now the output is:

    ym 1m2n s1 n1n2m
    

    Note that replaceFirst() expects String arguments, instead of char.