0

I'm trying to write a program that changes the case of two characters in a string (change uppercase to lowercase and vice versa).It compiled, but the string is the same.

String newChar1 = caseChanger("DcoderIsCool", 3); 
String newChar2 = caseChanger("DcoderIsCool", 8);  

I think the problem is with the method i used:

public static String caseChanger (String s, int ind) {
    if(!(Character.isUpperCase(s.charAt(ind)))) { 
        //checking if the character is uppercase or lowercase
        return s.substring(ind, ind + 1).toLowerCase();
    } else {
        return s.substring(ind, ind + 1).toUpperCase();        
    }
}

The output should have been "DcoDerIscool", but it's "DcoderIsCool" (the original string).

BumbleBee
  • 3
  • 3

3 Answers3

1

Hope I understood your question right.

below code will give you output DcoDerIsCool and DcoderIscool.

public static String caseChanger(String s, int ind) {

    char[] charArr = s.toCharArray();

    if (!(Character.isUpperCase(s.charAt(ind)))) {
        charArr[ind] = Character.toUpperCase(s.charAt(ind));
    } else {
        charArr[ind] = Character.toLowerCase(s.charAt(ind));
    }
    return String.valueOf(charArr);
}
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
0

I Think this is what you are looking for

public static String caseChanger (String s, int ind) {
    if((Character.isUpperCase(s.charAt(ind)))) { //checking if the character is uppercase or lowercase

        return new StringBuilder(s).replace(ind,ind+1,s.substring(ind, ind + 1).toLowerCase()).toString();
    }
    else {
        return new StringBuilder(s).replace(ind,ind+1,s.substring(ind, ind + 1).toUpperCase()).toString();        }
}

So you are changing only n charecter and returning those changed charecteres beside the extra not ! you are adding meaning your if condition is the other way arround. But what you are looking for is to replace the chars at the position you want in the original String. if im not mistaken. Hope it helps

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30
  • 1
    thank you! as suggested, i removed the "!" and it works now, but your code is more straight-forward, so i will also change the return statements :) – BumbleBee Jul 15 '19 at 11:05
  • 1
    Use StringBuilder, not StringBuffer. StringBuffer forces synchronization overhead on every method, which has no benefit in single-threaded logic, and rarely has any benefit even in multi-threaded logic. – VGR Jul 15 '19 at 15:59
0

You fetched the character from string but didn't placed back into string s.substring(ind, ind + 1).toLowerCase() is applied to single character

Instead doing return s.substring(ind, ind + 1).toLowerCase();

Replace the CaseChanged character back into the original string.

Rehan
  • 408
  • 1
  • 6
  • 17