Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

How do I extract substrings from string?

I have so expression that contains numbers and plus symbols:

string expression = 235+356+345+24+5+2+4355+456+365+356.....+34+5542;
List<string>  numbersList = new List<string>();

How should I extract every number substring (235, 356, 345, 24....) from that expression and collect them into a string list?

Upvotes: 1

Views: 148

Answers (4)

Nicholas Carey
Nicholas Carey

Reputation: 74375

Or this, a positive check for numeric sequences:

private static Regex rxNumber = new Regex( "\d+" ) ;
public IEnumerable<string> ParseIntegersFromString( string s )
{
    Match m = rxNumber.Match(s) ;
    for ( m = rxNumber.Match(s) ; m.Success ) ; m = m.NextMatch() )
    {
        yield return m.Value ;
    }
}

Upvotes: 1

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

Try this piece of code

string expression = "235+356+345+24+5+2+4355+456+365+356";
string[] numbers = expression.Split('+');
List<string> numbersList = numbers.ToList();

Upvotes: 1

kprobst
kprobst

Reputation: 16651

Something like:

string expression = "235+356+345+24+5+2+4355+456+365+356";
List<string> list = new List<string>(expression.Split('+'));

Upvotes: 3

Eric J.
Eric J.

Reputation: 150228

You can do something like

List<string> parts = expression.Split('+').ToList();

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

If there is any potential for white space around the + signs, you could so something a little more fancy:

List<string> parts = (from t in expression.Split('+') select t.Trim()).ToList();

Upvotes: 4

Related Questions