Parsing Problem.....

  • Thread starter Thread starter Wallace
  • Start date Start date
W

Wallace

Hai all,

In VC++,

CString str = " 4 76 1";
int nNo = atoi(str.Mid(0,8));

it returns nNo = 4 as output.... it returns the first integer
occurence and neglects the remaining character....


Similarly, In C#.NET I do the same as following....

string str = " 4 76 1";
int nNo = int.Parse(str.Substring(0, 8));

it is throwing the exception as "Input string is not in correct
format....."

How can i get the output as 4(i.e nNo = 4) in c#.net ????
Is there any other function other than parse, to fulfil this??

Please help... Thanx in advance...
Urgent..... Looking forward for the ur response....
 
Wallace wrote:

How can i get the output as 4(i.e nNo = 4) in c#.net ????
Is there any other function other than parse, to fulfil this??

Well, you could split the string on spaces. Look at the docs for
String.Split.

Jon
 
Hi Wallace,

string str = " 4 76 1";
int i=0;
string str_new;

while(str != ' ')
str_new = str;

int nNo = int.Parse(str_new);


you will get the output
nNo=4


Regards,
Ajith
 
Ajith said:
string str = " 4 76 1";
int i=0;
string str_new;

while(str != ' ')
str_new = str;

int nNo = int.Parse(str_new);


Did you try this code?

1) If str doesn't start with a space, it will tight-loop
2) str_new is never assigned
3) The string indexer is read-only.

I assume you meant code more like:
using System;
using System.Text;

class Test
{
static void Main()
{
string str = " 4 76 1";

StringBuilder builder = new StringBuilder();

int i=0;
// Get past leading spaces
while (str==' ')
{
i++;
}
// Copy non-spaces
while (str!=' ')
{
builder.Append(str);
i++;
}

int nNo = int.Parse(builder.ToString());
Console.WriteLine (nNo);
}
}

It's still probably not the code I'd use, but it does at least work.

Jon
 
thanx for ur suggestions and this one works fine....

string strInput1 = " 4 73 5 ");

int i1 = 0;
string strTemp1 = "";
string [] strArr1 = strInput1.Split(' ');
int Len1 = strArr1.Length;
for(i1 = 0; i1 < Len1; i1++)
{
strTemp1 = strArr1.GetValue(i1).ToString();
if( strTemp1 != "")
break;
}
if( i1 == Len1 )
{
nNoOfRecs = 0;
}
else
{
nNoOfRecs = Convert.ToInt32(strTemp1);
}
 
Wallace said:
thanx for ur suggestions and this one works fine....

string strInput1 = " 4 73 5 ");

int i1 = 0;
string strTemp1 = "";
string [] strArr1 = strInput1.Split(' ');
int Len1 = strArr1.Length;
for(i1 = 0; i1 < Len1; i1++)
{
strTemp1 = strArr1.GetValue(i1).ToString();
if( strTemp1 != "")
break;
}
if( i1 == Len1 )
{
nNoOfRecs = 0;
}
else
{
nNoOfRecs = Convert.ToInt32(strTemp1);
}

Here's a slightly more compact version which does the same thing:

nNoOfRecs = 0;

foreach (string x in strInput1.Split(' '))
{
if (x != "")
{
nNoOfRecs = int.Parse(x);
break;
}
}

Jon
 
Back
Top