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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99

3 Answers3

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);
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
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

Vitaly
  • 115
  • 8
0

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

String result = s.replaceAll("[pP]", "b");
eltabo
  • 3,749
  • 1
  • 21
  • 33