• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

trim a string

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.
1 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(" ")));
NewMom2BrandonAuthor Commented:
Thank you!!
Fernando SotoCommented:
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;


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now