1

I have a kinda simple problem, but I want to solve it in the best way possible. Basically, I have a string in this kind of format: <some letters><some numbers>, i.e. q1 or qwe12. What I want to do is get two strings from that (then I can convert the number part to an integer, or not, whatever). The first one being the "string part" of the given string, so i.e. qwe and the second one would be the "number part", so 12. And there won't be a situation where the numbers and letters are being mixed up, like qw1e2.

Of course, I know, that I can use a StringBuilder and then go with a for loop and check every character if it is a digit or a letter. Easy. But I think it is not a really clear solution, so I am asking you is there a way, a built-in method or something like this, to do this in 1-3 lines? Or just without using a loop?

minecraftplayer1234
  • 2,127
  • 4
  • 27
  • 57

5 Answers5

4

You can use a regular expression with named groups to identify the different parts of the string you are interested in.

For example:

string input = "qew123";
var match = Regex.Match(input, "(?<letters>[a-zA-Z]+)(?<numbers>[0-9]+)");
if (match.Success)
{
    Console.WriteLine(match.Groups["letters"]);
    Console.WriteLine(match.Groups["numbers"]);
}
steve16351
  • 5,372
  • 2
  • 16
  • 29
1

You can try Linq as an alternative to regular expressions:

string source = "qwe12";

string letters = string.Concat(source.TakeWhile(c => c < '0' || c > '9'));
string digits = string.Concat(source.SkipWhile(c => c < '0' || c > '9'));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

You can use the Where() extension method from System.Linq library (https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where), to filter only chars that are digit (number), and convert the resulting IEnumerable that contains all the digits to an array of chars, that can be used to create a new string:

string source = "qwe12";
string stringPart = new string(source.Where(c => !Char.IsDigit(c)).ToArray());
string numberPart = new string(source.Where(Char.IsDigit).ToArray());
MessageBox.Show($"String part: '{stringPart}', Number part: '{numberPart}'");

Source:

https://stackoverflow.com/a/15669520/8133067

Pedro Gaspar
  • 777
  • 8
  • 35
0

if possible add a space between the letters and numbers (q 3, zet 64 etc.) and use string.split otherwise, use the for loop, it isn't that hard

0

You can test as part of an aggregation:

var z = "qwe12345";
var b = z.Aggregate(new []{"", ""}, (acc, s) => {
  if (Char.IsDigit(s)) {
    acc[1] += s;
  } else {
    acc[0] += s;
  }
  return acc;
});
Assert.Equal(new [] {"qwe", "12345"}, b);
Paul D'Ambra
  • 7,629
  • 3
  • 51
  • 96