-3

If a string that contains integers and I want to split it based on integers occurrence. how to do that?

string test= "a b cdf 7654321;

then I want to store the integer and all words before it, like this

string stringBefore="";
// the integer will be last item
string integer="";  

Note:

in my case the integer always will be 7 digits

shmookh
  • 49
  • 4
  • What part of the split string do you want to use afterwards? What do possible input strings look like; are there variations in the structure/content of the input string(s)? You might guess it already, i am thinking of substring or regular expressions... –  Mar 30 '18 at 18:06
  • Is the integer always the last item of the string? – maccettura Mar 30 '18 at 18:14
  • Is the integer always the last item of the string? yes – shmookh Mar 30 '18 at 18:15
  • do you want the characters and numbers ? i mean do u want the result to be `abcdf` and `7654321` – Software Dev Mar 30 '18 at 18:20
  • do you want the characters and numbers ? yes I want both – shmookh Mar 30 '18 at 18:25
  • @shmookh He was asking if you wanted the results without any spaces. – Sudsy1002 Mar 30 '18 at 18:25
  • In your example both `stringBefore` and `integer` are empty strings. I don't think that's what you want..? – Rufus L Mar 30 '18 at 18:42
  • @RufusL I think that was the OP's way of saying I want the result to be two strings. OP marked me as correct and that was the assumption I made so who knows – maccettura Mar 30 '18 at 18:43

2 Answers2

3

You can use Regex.Split with a capture group to return the delimiter:

var ans = Regex.Split(test, @"("\d{7})");

If the number is at the end of the string, this will return an extra empty string. If you know it is always at the end of the string, you can split on its occurrence:

var ans = Regex.Split(test, @"(?=\d{7})");
NetMage
  • 26,163
  • 3
  • 34
  • 55
3

According to your comments the integer is always 7 digits and it is always the last item of the string.

In that case, just use Substring()

string test = "a b cdf 7654321";
string stringBefore = test.Substring(0, test.Length - 7); 
string integer = test.Substring(test.Length - 7);  

Substring just makes a string based on a portion of your original string.

EDIT

I was a little surprised to find there wasn't a built in way to easily split a string in to two strings based on an index (maybe I missed it). I came up with a LINQ extension method that achieves what I was trying to do, maybe you will find it useful:

public static string[] SplitString(this string input, int index)
{
    if(index < 0 || input.Length < index)
        throw new IndexOutOfRangeException();
    return new string[] 
    {
        String.Concat(input.Take(input.Length - index)),
        String.Concat(input.Skip(input.Length - index))
    };      
}

I think I would rather use a ValueTuple if using C# 7, but string array would work too.

Fiddle for everything here

Community
  • 1
  • 1
maccettura
  • 10,514
  • 3
  • 28
  • 35