0

I want to find integer value from a string. For example, given a String like "Ahmedabad to Gandhinagar Distance:29km(about 31 mins)"

I want to fetch only 29 from the given String because i want to compare this 29 kilometers to other kilometers.

2
  • Which language are you using? You specify both C# and Java. Is the string from which you're extracting the value regular - is it always in the same format? If so, you could find the ':' and extract the digits that follow it. Commented Apr 14, 2011 at 5:42
  • 1
    What is the language you want this answer for. Commented Apr 14, 2011 at 5:42

3 Answers 3

4

In C#, you can use a Regex.Match to pull out substrings if you use groups in the regex (note this is not tested...). There is probably a similar mechanism in Java, but I don't know it off the top of my head:

var myString = @"Ahmedabad to Gandhinagar Distance:29km(about 31 mins)";
var myRegex = @".*:(\d*)km.*";
var match = Regex.Match(myString, myRegex);

if (match.Success)
{
    // match.Groups contains the match "groups" in the regex (things surrounded by parentheses)
    // match.Groups[0] is the entire match, and in this case match.Groups[1] is the km value
    var km = match.Groups[1].Value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use this regex

/[:](\d+)/

and you'll have the match as 29. Here is a rubular link with your example.

Comments

0

Try this code in C#

            string str = "Ahmedabad to Gandhinagar Distance:29km(about 31 mins)";
            str = str.Substring(str.IndexOf(':')+1, str.IndexOf("km") - str.IndexOf(':')-1); ;
            int distance = Convert.ToInt32(str);

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.