How to convert the second letter of every word in a string to uppercase with Java

2 Answers

0 votes
public class MyClass {
    public static String convert_each_word_second_letter_of_string_to_uppercase(String s) {
        String[] words = s.split(" ");
        String result = "";
 
        for(String w: words) {
            result += String.valueOf(w.charAt(0)) + 
                      Character.toUpperCase(w.charAt(1)) + 
                      w.substring(2) + 
                      " ";
        }
         
        return result;
    }  
    public static void main(String args[]) {
        String s = "java swift php python cpp";
          
        s = convert_each_word_second_letter_of_string_to_uppercase(s);
 
        System.out.println(s);
    }
}
  
  
  
  
/*
run:
  
jAva sWift pHp pYthon cPp 
 
*/

 



answered Jun 11, 2021 by avibootz
edited Jun 14, 2021 by avibootz
0 votes
public class MyClass {
    public static String convert_each_word_second_letter_of_string_to_uppercase(String s) {
        char arr[] = s.toLowerCase().toCharArray();
 
        arr[1] = Character.toUpperCase(arr[1]);
        
        for (int i = 0; i < arr.length; i++) {
            if (Character.isWhitespace(arr[i]) && Character.isLetter(arr[i + 1]))
                arr[i + 2] = Character.toUpperCase(arr[i + 2]);
        }
         
        return new String(arr);
    }  
    public static void main(String args[]) {
        String s = "java swift php python cpp";
         
        s = convert_each_word_second_letter_of_string_to_uppercase(s);
 
        System.out.println(s);
    }
}
  
  
  
  
/*
run:
  
jAva sWift pHp pYthon cPp
 
*/

 



answered Jun 11, 2021 by avibootz
edited Jun 12, 2021 by avibootz

Related questions

...