0

I've got a very long java string and I'm trying to replace half of the occurrences of a particular word with its reverse.

So, if the string is "hello my friend hello", the output if I run it with the word "hello" should give something like "hello my friend olleh".

I know that I can reverse a word with

new StringBuilder(str).reverse().toString()

and that I can use

Str.replaceAll("hello", "olleh")

to modify the string. But how can I tell replaceAll to only substitute half of the occurrences of hello? Is there a way to input a probability in replaceAll or loop through the text and stop at every occurrence?

Alessandro
  • 4,000
  • 12
  • 63
  • 131
  • Your problem is loosely defined. Does it need to be exactly one half ? If so, how to decide which occurrence to replace and which not to replace ? If it's not exactly one half, how approximate can the result be ? Etc – Dici Mar 07 '17 at 22:38
  • @Dici I meant exactly half, but a more uneven split is also fine – Alessandro Mar 07 '17 at 22:48
  • Note: if you're replacing strings without any regex special characters, use `String.replace`, not `String.replaceAll`. – Andy Turner Mar 07 '17 at 22:50

2 Answers2

4

If you want to replace half of the occurrences, one way of doing this without counting the number of occurrences up front is to replace every other occurrence (skip one, replace one, skip one, replace one...).

String replaceHalf(String input, String search) {
  String reversed = new StringBuilder(search).reverse().toString();
  StringBuilder sb = new StringBuilder(input);
  int pos = -search.length();
  while (true) {
    // Find the next occurrence...
    pos = input.indexOf(search, pos + search.length());
    if (pos == -1) break;

    // ...but ignore it, and find the next occurrence.
    pos = input.indexOf(search, pos + search.length());
    if (pos == -1) break;

    sb.replace(pos, pos + search.length(), reversed);
  }
  return sb.toString();
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

1 - count how much substring "hello"

see Occurrences of substring in a string

How about using StringUtils.countMatches from Apache Commons Lang?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

2 - then iterate to N/2 with

replaceFirst, or indexOf, and use your probability model ...

Community
  • 1
  • 1