-3

I want to replace the character ‘e’ with ‘E’ in a word “Hello”. I'm reading the arguments from the prompt.

class LowToUpCase{
    public static void main(String[] args){
        if (args.length != 0) {
            String str = args[0];
            str = str.substring(1,2);
            System.out.println(str.toUpperCase());  
        }else{
            System.out.println("Give arguments");
        }
    }
}

Im getting the output as the Capitalised E only. But I'm not getting any idea how to get the output as hEllo . Please give me the hint to get the needed output.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Anu
  • 11
  • 2
  • [StringBuffer](https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html) might be good for you. – RaminS Jun 18 '16 at 18:50
  • 2
    He should use [StringBuilder](https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) instead of StringBuffer. – blacktide Jun 18 '16 at 18:51
  • See http://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string. – jarmod Jun 18 '16 at 18:51
  • @Casey Oh, right. My bad. – RaminS Jun 18 '16 at 18:52
  • How should your program behave if the input is something other than Hello? Should it convert all e characters to E, or only the second character of the input? And what if the input is only a single letter? – Dawood ibn Kareem Jun 18 '16 at 18:57

4 Answers4

4

Why not replace the lower case e with its uppercase counterpart?

String str = args[0];
str = str.replace('e', 'E');
System.out.println(str);

Docs for String.replace().

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
2

You can use the replace() method from the String class.

class LowToUpCase{

   public static void main(String[] args){

   if (args.length != 0)
    {
      String str = args[0];
      str = str.replace('e', 'E');
      System.out.println(str);

    }else{
    System.out.println("Give arguments");
    }
  }
}
Andres Elizondo
  • 331
  • 3
  • 15
2

It appears that you also want to lowercase (at least) the first letter (so don't forget to call toLowerCase() on the input). I would prefer a StringBuilder (a mutable sequence of characters over modifying an immutable String) and something like,

StringBuilder sb = new StringBuilder(args[0].toLowerCase());
sb.replace(1, 2, sb.substring(1, 2).toUpperCase());
System.out.println(sb);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
String s="Hello";
String value=s.replace( 'e' ,'E');
Vishal Sharma
  • 1,051
  • 2
  • 8
  • 15