0

So basically if I have string a = "asd333"; I want to split this string into two strings

string b = "asd" and string c = "333"

for example string a = "aaa 555";string[]b = a.Split(' '); will make

b[0]="aaa" and b[1] = "555"

But this is not what i want i want to split string into two string withouth loosing characters and split it before a number

This is my code so far

 string text = textBox4.Text.ToString();

            char[] whitespace = new char[] { ' ','\t'  };
            string[] temp = text.Split(whitespace);

But i want to change it so string[] temp equals two string first is letters and second is numbers

2
  • 2
    so you are trying to remove spaces, then split by space ? Commented Jul 17, 2014 at 14:08
  • Why are you replacing " " with string.Empty? Why not just split on " "? Commented Jul 17, 2014 at 14:08

3 Answers 3

1

I think it's not the best method, but it works

    string a = "aaa333aaa333aaa22bb22bb1c1c1c";

    List<string> result = new List<string>();

    int lastSplitInedx = 0;
    for (int i = 0; i < a.Length-1; i++)
    {
        if (char.IsLetter(a[i]) != char.IsLetter(a[i + 1]))
        {
            result.Add(a.Substring(lastSplitInedx, (i + 1) - lastSplitInedx));
            lastSplitInedx = i+1;
        }
        if (i+1 == a.Length-1)
        {
            result.Add(a.Substring(lastSplitInedx));
        }
    }

    foreach (string s in result)
    {
        Console.WriteLine(s);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Get the matched group from index 1 and 2.

String literals for use in programs:

C#

@"(\D+)\s*(\d+)"

1 Comment

Split by this regex (?<=\D)\s*(?=\d). Here is DEMO
-1

Search for the integer in the string and split the string at that position

string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.