Wednesday, April 7, 2010

CodingBat string manipulation problems - Part 1

I had fun doing all the Java exercises on the other week (all 264 at last count). None of them were truly hard, but I challenged myself to stubbornly use regex whenever possible, but also especially when it actually leads to a much better solution.

This part shows some of the easier ones.

zipZap: Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone.
public String zipZap(String str) {
  return str.replaceAll("z.p", "zp");
Why regex? This is why!

Captured group in replacement string

doubleChar: Given a string, return a string where every char is doubled.
public String doubleChar(String str) {
  return str.replaceAll("(.)", "$1$1");
The most basic use of captured group in replacement string.

extraFront: Given a string, return a new string made of 3 copies of the first 2 chars of the original string. If there are fewer than 2 chars, use whatever is there.
public String extraFront(String str) {
  return str.replaceAll("(..?).*", "$1$1$1");
front22: Given a string, take the first 2 chars and return the string with the 2 chars added at both the front and back. If the string length is less than 2, use whatever chars are there.
public String front22(String str) {
  return str.replaceAll("(..?)(.*)", "$1$1$2$1");
lastTwo: Given a string of any length, return a new string where the last 2 chars, if present, are swapped.
public String lastTwo(String str) {
  return str.replaceAll("(.*)(.)(.)", "$1$3$2");
These solutions show that regex offers not only conciseness, clarity, and readability, but also the convenience of not requiring any special handling for input strings less than two characters long.

The start and end of string anchors

This is an alternative solution to lastTwo (see above), using the $ end of string anchor to match and capture only the last two characters of the string.
public String lastTwo(String str) {
  return str.replaceAll("(.)(.)$", "$2$1");

withouEnd2: Given a string, return a version without both the first and last char of the string. The string may be any length, including 0.
public String withouEnd2(String str) {
  return str.replaceAll("^.|.$", "");

No comments:

Post a Comment