0

Below code is to convert upper case to lower case and vice vers?

  if(s1.charAt(i)>=97 && s1.charAt(i)<=122){
     s1.charAt(i)=s1.charAt(i)-32;
  }
  else if(s1.charAt(i)>=65 && s1.charAt(i)<=90){
      s1.charAt(i)=s1.charAt(i)+32;
  }

Please refer above and help what is the issue with this program?

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • 2
    Possible duplicate of [Replace character in StringBuilder](https://stackoverflow.com/questions/16579273/replace-character-in-stringbuilder) – Shubhendu Pramanik Jun 29 '18 at 10:08
  • 1
    what is `s1`? a `String`? String is immutable, cannot be changed; anyway `charAt` is a method that returns a char, you cannot assign a new value to that returned value. – user85421 Jun 29 '18 at 10:15

2 Answers2

2

You have a problem here :

 s1.charAt(i) = s1.charAt(i) - 32;
 ------------   -----------------
      1                2

Here there are two problems :

  • First thing, the 2nd part return an int, and you try to assign it to a char
  • Second you can't make an assign like that

Instead I would use :

String s1 = "AbCd";
//create a char array
char[] array = s1.toCharArray();
//loop over this array, and work just with it
for (int i = 0; i < array.length; i++) {
    if (array[i] >= 'a' && array[i] <= 'z') {
        array[i] = (char) (s1.charAt(i) - 32);//<--------------------------note this
    } else if (s1.charAt(i) >= 'A' && s1.charAt(i) <= 'Z') {
        array[i] = (char) (s1.charAt(i) + 32);
    }
}

//when you end, convert that array to the String
s1 = String.valueOf(array);//output of AbCd is aBcD

Beside I would like to use :

String result = "";
for (int i = 0; i < array.length; i++) {
    if (Character.isLowerCase(array[i])) {
        result += Character.toUpperCase(s1.charAt(i));
    } else {
        result += Character.toLowerCase(s1.charAt(i));
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Your code doesn't even compile, you can't do s1.charAt(i) = 'x', because s1.charAt is not a variable, you can't just assign anything to it.

To replace a character by index in a String, do:

new StringBuilder(yourString).setCharAt(characterIndex, 'x')

I suggest using some IDE like Intellij or Eclipse, it will tell you about compile errors like those.

Shadov
  • 5,421
  • 2
  • 19
  • 38