trim a string

Posted on 2006-04-19
Last Modified: 2010-04-16
I need to trim a string. What I need to trim off is anything following the first number(s)

for example

1 black cat jumped false true 1
12 red cat sat true false 2
123 Yellow dog sat true false 2

So all I want is the 1, 12 or 123.

How do I go about doing this. So basically anything following the first number. I can't set a length for the number becasue it is incremented based on the number of entries the user adds on another form.
Question by:NewMom2Brandon
    LVL 5

    Accepted Solution

    If then is a space always after the number then use the substring method

    string myString = "1 black cat jumped false true 1";

    int myNumber = Convert.ToInt32(myString.Substring(0,myString.IndexOf(" ")));
    LVL 2

    Author Comment

    Thank you!!
    LVL 62

    Expert Comment

    by:Fernando Soto
    Hi NewMom2Brandon;

    This solution uses Regular Expressions. The variable will have the results, the first digits in the string.

    using System.Text.RegularExpressions;

          string input = "1 black cat jumped false true 1";
          Match m = Regex.Match(input, @"\s*?(\d+)");
          string results = m.Groups[1].Value;


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Article by: Ivo
    Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
    This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    This video discusses moving either the default database or any database to a new volume.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now