Buena
Buena

Reputation: 2491

How to parse specific characters of a string to integer?

string abc = "07:00 - 19:00"
x  = int.Parse(only first two characters) // should be 7
y  = int.Parse(only 9th and 10th characters) // should be 19

How could I say this, please ?

Upvotes: 1

Views: 1199

Answers (2)

Adil
Adil

Reputation: 148110

Use Substring method of string class to extract the required set of characters.

string abc = "07:00 - 19:00";
x  = int.Parse(abc.Substring(0,2)); // should be 7
y  = int.Parse(abc.Substring(8,2)); // should be 19

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062560

There is no int.Parse that takes a range, so either:

  • write your own parser (yeuch)
  • use Substring first, and then use int.Parse on the substring

so:

x = int.Parse(abc.Substring(0,2));

etc

Upvotes: 3

Related Questions