How to Split a String between Numbers and Letters?

Problem Formulation: A list of letters and digits is provided. How to split up the string using the border between a letter and a number, and inversely, into substrings of either letters or numbers.

Split string without a predefined function

Divide the string str into three segments: a numeric segment; an alphabetic segment; and a segment with special characters.

Examples


Steps

  1. Determine the string's length.
  2. Individually scan each character (ch) in a string
    • Add it to the res1 string if (ch is a digit).
    • Alternately, if (ch is an alphabet), add a string to res2.
    • Else add it in string res3.
  3. Print every string. We shall have three strings: one with a numeric component, one without a numeric component, and one with special characters..

Program

Output:

How to Split a String between Numbers and Letters

Time Complexity: The preceding approach has an O(n) time complexity, where n is the length of the string.

Auxiliary Space: The space complexity of give code is O(n), where n is the string's length.

We can also split string on a regular expression like (?<=\D)(?=\d). Like this:

Program

Output:

How to Split a String between Numbers and Letters

So there are many ways to split string between number and characters. That are following:

Method: 1

Output:

How to Split a String between Numbers and Letters

Method: 2

Output:

How to Split a String between Numbers and Letters

Method: 3

Output:

How to Split a String between Numbers and Letters




Latest Courses