Playing with Char Array
24 October 2024 at 09:23
// 1. REMOVING UNWANTED SPACE // 2. CAPITALIZE EACH WORD
package taskPkg; import java.util.Scanner; public class PlayingWithCharAr { public static void main(String[] args) { // 1. REMOVING UNWANTED SPACE // 2. CAPITALIZE EACH WORD Scanner scn = new Scanner(System.in); System.out.println("Enter a sentence..."); String sentence = scn.nextLine(); scn.close(); char[] sen = sentence.toCharArray(); PlayingWithCharAr obj = new PlayingWithCharAr(); obj.removeSpace(sen); obj.wordStartWithCaps(sen); } private void removeSpace(char[] words) { int k = 0, n = words.length; System.out.print("Removed unwanted spaces :"); while (k < n && words[k] == ' ') k++; for (; k < n - 1; k++) { if (!(words[k] == ' ' && words[k + 1] == ' ')) System.out.print(words[k]); } if (words[n - 1] != ' ') System.out.print(words[n - 1]); System.out.println(); } private void wordStartWithCaps(char[] words) { int i = 0, n = words.length; System.out.print("Capitalize Each Word :"); if (words[i] != ' ') System.out.print((char) (words[i] - 32)); for (i = 1; i < n; i++) { if (words[i - 1] == ' ' && words[i] != ' ' && (words[i] >= 'a' && words[i] <= 'z')) System.out.print((char) (words[i] - 32)); else System.out.print(words[i]); } } }
OUTPUT: