Site icon codippa

Convert each alternate character of a string to upper case in java

In this article, we will look at java program to convert alternate character of a string to upper case with explanation and sample output.
Algorithm
1. Get all characters of the string.
2. Iterate over the characters one by one.
3. In each iteration, check the position of character.
4. If its position is odd(such as 1, 3, 5, 7 etc.) since character position starts from 0, convert is to upper case.

Java Program
Implementation of above algorithm in a java program will be as below.

public class CharacterConverter { 
  public static void main(String[] args) { 
    // initialize string 
    String sample = "codippa"; 
    // initialize string buffer to hold updated string 
    StringBuffer updatedString = new StringBuffer(); 
    // get array of characters in string 
    char[] characters = sample.toCharArray(); 
    // iterate over characters 
    for (int index = 0; index < characters.length; index++) { 
      // get current character 
      char c = characters[index]; 
      // check if position of this character is odd 
      if (index % 2 != 0) { 
        // convert it to upper case 
        c = Character.toUpperCase(c); 
      } 
      // append character to string buffer 
      updatedString.append(c); 
    } 
    System.out.println("Modified string is: " + updatedString.toString()); 
  } 
}

Above program will print the following output

Modified string is: cOdIpPa

From the output, it is clear that alternate characters of the string have been converted to upper case.

If you just want to print the string to console, then there is no need of adding the characters to the StringBuffer object, just print them using System.out.print(c) inside the loop.

Let’s tweak in

  1. Indexes of characters in a string start from 0 and move from left to right. Thus, character at left most end of a string will have an index of 0.
  2. If you want to convert alternate characters with first letter capitalized, then instead of checking for odd character, check for even character and capitalize only if the character is at even position since in that case, the characters to be capitalized will be at positions 0, 2, 4, 6 and so on.
  3. The above program capitalizes alternate characters but it is also possible to toggle the case of alternate characters, that is, capitalize them if they are in lower case and vice-versa.
    For this, check the case of character using Character.isLowerCase and Character.toUpperCase methods and convert the case accordingly.
Exit mobile version