0

Removing every other character in a string using Java regex

The code at the above link clearly details how to remove every other character from a string, however, I do not understand how it works and would like to so I can use it in the future. The Oracle page for replaceAll does not mention this type of use. What is the function of the $1 and the periods and the parentheses (I get that the one in parentheses is the one that is kept, but why, etc.? Thanks! :)

Community
  • 1
  • 1
  • `Do I have to use a loop?` - that is how you make your code generic. When done properly it doesn't matter is your string has 3 or 300 characters. – camickr Oct 13 '15 at 18:55
  • Yeah why not. Just use a for loop running through the string and adding every other character to a different string. or there might be some regex expression you can do. – 3kings Oct 13 '15 at 18:56
  • Detail about search patterns can be found in the documentation of the [`Pattern`](http://docs.oracle.com/javase/8/docs/api/?java/util/regex/Pattern.html) class, the replacement is documented in the backend method [`appendReplacement`](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#appendReplacement-java.lang.StringBuffer-java.lang.String-) – Holger Oct 13 '15 at 19:41
  • Please be aware that questions have to be self-contained. Now it completely depends on another SO question... – Deduplicator Oct 13 '15 at 19:52

1 Answers1

-2

Just use a loop to remove every other character.

for (int i = 0; i<yourString.length(); i++){
if (i % 2 != 0){
yourString.deleteCharAt(i);
}
}
Remixt
  • 597
  • 6
  • 28