5 Replies - 2601 Views - Last Post: 23 February 2009 - 11:43 AM Rate Topic: -----

#1 girireddy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-February 09

Convert String to Int

Post icon  Posted 21 February 2009 - 04:33 AM

I would like to convert a string of numbers "123456-012" to int and derive 012. How to achieve this in C#. Thanks in advance for any help.
Is This A Good Question/Topic? 0
  • +

Replies To: Convert String to Int

#2 Todilo  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 85
  • Joined: 13-November 07

Re: Convert String to Int

Posted 21 February 2009 - 06:02 AM

String s = "123456-012";
string[] numbers = s.Split('-');
//if you know it is always two parts:
int numPartOne,numPartTwo;
TryParse(numbers[0],out numPartOne);
TryParse(numbers[1],out numPartTwo);



Hope it helps
Was This Post Helpful? 0
  • +
  • -

#3 sonia.sardana  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 132
  • Joined: 01-June 08

Re: Convert String to Int

Posted 21 February 2009 - 09:45 AM

 String sWholeNumb = "123456-012";
	string sFirstPart;
	string sSecondPart;
	string[] sArr;
	sArr = sWholeNumb.Split('-');
	sFirstPart = sArr[0];
	sSecondPart = sArr[1];


Was This Post Helpful? 0
  • +
  • -

#4 Ryan Marfone  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 87
  • Joined: 23-February 09

Re: Convert String to Int

Posted 23 February 2009 - 09:44 AM

For an extra layer of security you may want to compare your string with a regular expression to verify it uses the format your expecting.
Was This Post Helpful? 0
  • +
  • -

#5 Moonbat  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 36
  • View blog
  • Posts: 424
  • Joined: 30-June 08

Re: Convert String to Int

Posted 23 February 2009 - 10:27 AM

First you should use String.Split() to cut the input into two parts. Use the - character as a delimiter. You should have a string array variable to hold the output.

I would use the Convert.ToInt32 method to convert the second string in your string array into an integer. Make sure to have an integer variable ready to hold the output of this function.
Was This Post Helpful? 0
  • +
  • -

#6 Ryan Marfone  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 87
  • Joined: 23-February 09

Re: Convert String to Int

Posted 23 February 2009 - 11:43 AM

Here is how I would do it.

internal List<int> convertToInt(string inputString, char delimiter)
{
	   var intList = new List<int>();
	   var strings = inputString.Split(delimiter);
	   foreach (string str in strings)
	   {
		   try
		   {
			   intList.Add(Convert.ToInt32(str));
		   }
		   catch (Exception ex)
		   {
			   throw ex;
		   }
	   }
	   return intList;
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1