Deleting characters matching a pattern

Arduino:
Deleting characters matching a pattern

How to:

Let’s say we want to drop all numeric digits from our string. We’ve got a string with some random numbers, and we’re going after a clean, letters-only result.

void setup() {
  Serial.begin(9600);

  // Our initial string with numbers
  String stringWithNumbers = "Ar3du1n0 1s aw3som3!";
  String cleanedString = deletePattern(stringWithNumbers, "0123456789");

  // Print the cleaned string
  Serial.println(cleanedString);
}

void loop() {
  // Nothing to do here
}

String deletePattern(String str, String pattern) {
  for (unsigned int i = 0; i < pattern.length(); i++) {
    str.replace(String(pattern[i]), "");
  }
  return str;
}

If you upload and run this on your Arduino, you’ll see the string without numbers in the serial monitor:

Arduino is awesome!

Deep Dive

Removing characters matching a specific pattern isn’t a new concept. Early programming languages had functions to process and manipulate strings. In Arduino, although a high-level function for pattern deletion doesn’t exist natively, we can create our custom logic, like in the deletePattern function above.

There are alternatives in other languages, such as regex (regular expressions) in Python or JavaScript, but Arduino’s coding environment is more basic. It doesn’t include regex functions out of the box, mainly due to its limited processing power and memory.

Under the hood, our deletePattern function iterates through our pattern string, uses the String.replace() method to search for the current character, and replaces it with an empty string, therefore “deleting” it from our original string.

See Also