[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 152
  • Last Modified:

How to separate the words and number from a string?

I am working on C# and I am required to separate the words and number from a string.  It does not have any delimiter to separate it.

For example the format of string is page12345 and I am required to separet it as string 1 as page and string 2 as 12345.  Can you please guide me how can I achieve this?

Thanks,
D.
0
developer2012
Asked:
developer2012
2 Solutions
 
Kyle AbrahamsSenior .Net DeveloperCommented:
This will loop over each character in the string, test if it's a digit, and then add it to the appropriate string.

p1a2g3e4
string1 = "page" / string2 = "1234"

1234page
string 1 = "page" / string2 = "1234"

page1234
string1 = "page" / string2 = "1234"


 string mainString;
        string string1 = "";
        string string2 = "";
        
        foreach (char c in mainString.ToCharArray())
        {
            if (!Char.IsDigit(c))
                string1 += c;
            else
                string2 += c;
        }
      

Open in new window

0
 
käµfm³d 👽Commented:
You could also use regular expressions for this task:

e.g.

using System.Text.RegularExpressions;

...

string word;
string number;
string input = "page1234";
MatchCollection matches = Regex.Matches(input, "(?<word>[a-zA-Z]+)|(?<number>[0-9]+)");

foreach (Match m in matches)
{
    if (!string.IsNullOrWhitespace(m.Groups["word"].Value))
    {
        word = m.Groups["word"].Value;
    }
    else if (!string.IsNullOrWhitespace(m.Groups["number"].Value))
    {
        number = m.Groups["number"].Value;
    }
}

Open in new window


I use an OR condition ( | ) to match one of two groups. The "word" group [ (?<word>...) ] matches against one or more ( + ) letters--upper- and lowercase ( [a-zA-Z] ). The "number" group [ (?<number>...) ] matches against one or more ( + ) numeric digits ( [0-9] ). After the matching runs, I just check to see which group actually captured something, and then assign it to the appropriate variable.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now