Replace first letter of each word with another letter in Java

Published by user on

In this post, we will look at how to replace the first letter of each word with another letter in Java.

Logic:

  • Convert str to char array
  • Iterate char array and find the letters whose previous letter is space
  • Replace the letter with the new character
  • Convert char array back to String

Program

Let’s have a look at the program.

// Java program to demonstrate
// how to replace first character
// of each word with another
// character
public class ReplaceFirstLetter {
	public static void main(String[] args) {

		String str = "java is the best programming language";

		System.out.println("Actual String = " + str);
		// get the char array from str
		char[] charArr = str.toCharArray();
		char newChar = 'P';
		boolean isPreviousCharSpace = true;

		for (int index = 0; index < charArr.length; index++) {

			// check if the char is a letter
			if (Character.isLetter(charArr[index])) {

				// if the previous character
				// is space then replace the char
				// with another character
				if (isPreviousCharSpace) {
					// replace char with newChar
					charArr[index] = newChar;
					// reset the flag
					// as we already replaced the char
					isPreviousCharSpace = false;
				}
			} else {
				// check if char is space
				isPreviousCharSpace = true;
			}
		}

		// print the replaced string
		System.out.println("Replaced String = " + String.valueOf(charArr));
	}
}

Output

Actual String = java is the best programming language
Replaced String = Pava Ps Phe Pest Programming Panguage
Categories: Java