Solved

Converting a String to Int[]

Posted on 2007-11-22
10
514 Views
Last Modified: 2007-11-22
I have the code below, and I am having some weird behaviour when trying to convert a string to an int array. I know all values in the string are numbers and would just like to convert them into an int array so I can do some LUHN checking.

Some issues

The first digit in convert is 4
when I do:

char test = convert[i];

I get 52'4'

where 52 is the ASCII value for 4.

System.Convert.ToInt32(convert[i])

I get 52 where I am really looking for 4.


If I do:

Any ideas?
public static int[] ConvertString(string convert)

        {

            int[] digits = new int[convert.length];
 

            for (int i = 0; i < convert.Length; i++)

            {

                digits[i] = System.Convert.ToInt32(convert[i]);

            }
 

            return digits;

        }

Open in new window

0
Comment
Question by:directxBOB
  • 4
  • 2
  • 2
  • +2
10 Comments
 
LVL 7

Expert Comment

by:lucky_james
ID: 20334292
52'4'....
you need 4...you have got 52.
then you can find for ' and have 4.
you can you IndexOf method of string class, get this 4 in another string and can convert the new formed string to integer.
0
 
LVL 7

Expert Comment

by:lucky_james
ID: 20334304
seems like you want only 4 then you can use :
str.Remove(0, str.IndexOf("'')); // this would remove 52'
str.Substring(0, str.Length -1); // this would remove last '
now str would have 4 only.

hope it helps.
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20334310
The best way is to use string.Split() method to separate elements, and a List to build the array dynamically:
public static int[] ConvertString(string convert)

{

    string[] elems = convert.Split('\'');

    List<int> list = new List<int>;
 

    foreach (string s in elems)

    {

         if (s.Length > 0)

              list.Add(Convert.ToInt32(s));

    }

    return list.ToArray();

}

Open in new window

0
 
LVL 20

Expert Comment

by:REA_ANDREW
ID: 20334312
I believe that this function will be better for you I have just made.  This will only add digits to an int array and not fallover if your string to convert is l9ike 123456H

Andrew
        static int[] ConvertString(string convert)

        {

            List<int> intList = new List<int>();

            foreach (char c in convert)

            {

                if (char.IsDigit(c))

                    intList.Add((Int32)Char.GetNumericValue(c));

            }

            return intList.ToArray();

        }

Open in new window

0
 
LVL 40

Accepted Solution

by:
evilrix earned 400 total points
ID: 20334314
Subract '0' from the char returned by convert[i]
public static int[] ConvertString(string convert)

{

    int[] digits = new int[convert.Length];
 

    for (int i = 0; i < convert.Length; i++)

    {

        digits[i] = System.Convert.ToInt32(convert[i] - '0');

    }
 

    return digits;

}

static void Main(string[] args)

{

    ConvertString("01234");

}

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 20

Assisted Solution

by:REA_ANDREW
REA_ANDREW earned 100 total points
ID: 20334318
Oh and

Char.GetNumericValue

Solves that issue you are experiencing about the code being returned and not the actual value of the char

Andrew :-)
0
 

Author Comment

by:directxBOB
ID: 20334338
char x = 9;    //Character '9' = ASCII 57
int b;

b = x - '0';   //That is '9' - '0' = 57 - 48 = 9
0
 
LVL 20

Expert Comment

by:REA_ANDREW
ID: 20334406
Bit of useless info but comparing both my function and that of evilrix , which both work I might point out, BUT

I am surprised to see that evilrix's function is on average 3.9 milliseconds faster than mine.  

foreach loops just have performance hits everywhere lol
0
 
LVL 40

Expert Comment

by:evilrix
ID: 20334443
I suspect the difference is the overhead in calling Char.GetNumericValue and Char.IsDigit
0
 
LVL 20

Expert Comment

by:REA_ANDREW
ID: 20334451
true :-)

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What is Thread.Sleep? 5 46
Runtime Exceptions when trying to submit data 28 37
Turn on intranet settings 1 39
Help with C#, MVC, razor. 6 23
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now