0

I am writing a java program in which a user enters a series of words that changes every ‘p’ to a ‘b’ in the sentence (case insensitive) and displays the output.

I try to use replace function but it is not case insensitive

String result = s.replace('p', 'b');

I expect the output boliticians bromised, but the actual outputs is Politicians bromised.

1
  • 1
    can you use replace twice for p and P? Commented Jun 24, 2019 at 7:50

3 Answers 3

1

replace is case sensitive only.

There is no "simple" way to do this: you could do two replacements, but that constructs an intermediate string.

String result = s.replace('p', 'b').replace('P', 'B');

I would do this by iterating the character array:

char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; ++i) {
  switch (cs[i]) {
    case 'p': cs[i] = 'b'; break;
    case 'P': cs[i] = 'B'; break;
  }
}
String result = new String(cs);

If you wanted to write a method to do this for non-hardcoded letters, you could do it like:

String method(String s, char from, char to) {
  char ucFrom = Character.toUpperCase(from);  // Careful with locale.
  char ucTo = Character.toUpperCase(to);

  char[] cs = s.toCharArray();
  for (int i = 0; i < cs.length; ++i) {
    if (cs[i] == from) { cs[i] = to; }
    else if (cs[i] == ucFrom) { cs[i] = ucTo; }
  }
  return new String(cs);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it using regex, see Q&A - How to replace case-insensitive literal substrings in Java or you can use replace twice for p and P

Comments

0

You can use replaceAll instead so you can use a regular expression:

String result = s.replaceAll("[pP]", "b");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.