简体   繁体   中英

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?

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();

Something like:

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

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();

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 ;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM