public class PracticeWithLoops { /** * @param args */ public static void main(String[] args) { System.out.println(countChar('a', "Today is Tuesday")); System.out.println(makeUppercase('a', "a cat")); System.out.println(firstLetters("one two three")); } /** * Returns the number of times the given character appears in the given * string * * @param c * the character to find * @param s * the string to check */ public static int countChar(char c, String s) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { count++; } } return count; } /** * Returns the string that is s where all of the occurrences of c are * replaced with c uppercase (e.g. if s is "a cat" and c is 'a', the method * returns "A cAt") * * @param c * the character to make uppercase * @param s * the string to process */ public static String makeUppercase(char c, String s) { String s2 = ""; for (int i = 0; i < s.length(); i++) { char letter = s.charAt(i); if (letter != c) { s2 += letter; } else { s2 += Character.toUpperCase(c); } } return s2; } /** * Returns a string that contains the first letter of each word of the given * string * * @param s * the string to process */ public static String firstLetters(String s) { String first = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // take it only if c is a letter if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { // and c is preceded by a space or is at index 0 if (i == 0 || s.charAt(i - 1) == ' ') { first += c; } } } return first; } }