How to split an integer number into a string?

Asked

Viewed 74 times

-1

String following:

11 blabalba, balbalba balballbal  baba
12 balbal13, afafaf14 1414adad1414

I want you to return something like this (separated by split):

array 0: 11

array 1: blabalba, balbalba balballbal  baba

Second line:

array 0: 12

array 1: balbal13, afafaf14 1414adad1414

Always in first position.

1 answer

2

You can use something like this:

public static Tuple<int, string, bool> CustomSplit(string text)
{
    int val = 0;
    string aux = "";
    string res = null;
    for(int i = 0; i < text.Length; i++)
    {
        if(text[i] >= 48 && text[i] <= 57)
        {
            aux += text[i];
            continue;
        }
        res = text.Substring(i);
        break;
    }
    bool ok = int.TryParse(aux, out val);
    return new Tuple<int, string, bool>(val, res, ok);
}

To use you just need to call him:

string teste1 = "11 blabalba, balbalba balballbal  baba";
string teste2 = "12 balbal13, afafaf14 1414adad1414";

Tuple<int, string, bool> res = CustomSplit(teste1);
Console.WriteLine("\nItem1: "+res.Item1+"\nItem2: "+res.Item2+"\nItem3: "+ res.Item3);

res = CustomSplit(teste2);
Console.WriteLine("\nItem1: "+res.Item1+"\nItem2: "+res.Item2+"\nItem3: "+ res.Item3);

It will return one more variable bool confirming if you found and were able to convert the number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.