开发者

How to convert string into int array in C#

I am making a credit card validator program in which I am asking for a string which is going to be a 16 digit number (credit card #) and I want to convert that into an int array. How do I do that? I need to then multiply every other digit starting from the first digit by 2.

char[] creditNumbers = creditCardNumber.ToCharArray();

creditNumbers[0] = (char)((int)(creditNumbers[0] * 2));
creditNumbers[2] = (char)((int)(creditNumbers[2] * 2));
creditNumbers[4] = (char)(开发者_JAVA百科(int)(creditNumbers[4] * 2));
creditNumbers[6] = (char)((int)(creditNumbers[6] * 2));
creditNumbers[8] = (char)((int)(creditNumbers[8] * 2));

This is what I made so far but my casting is not done properly. How do I fix the problem?


To just get the int array, I would do this:

creditCardNumber.Select(c => int.Parse(c.ToString())).ToArray()

To check the number using the Luhn algorithm, you could do this:

bool IsValid(string creditCardNumber)
{
    var sum = creditCardNumber.Reverse()
                              .Select(TransformDigit)
                              .Sum();

    return sum % 10 == 0;
}

int TransformDigit(char digitChar, int position)
{
    int digit = int.Parse(digitChar.ToString());
    if (position % 2 == 1)
        digit *= 2;

    return digit % 10 + digit / 10;
}


var intArray = creditCardNumber.ToCharArray().Select(o => int.Parse(o.ToString())).ToArray();
var result = new List<int>();

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

    if((i % 2) == 0)
      result.Add(intArray[i] * 2);
    else
        result.Add(intArray[i]);
}

Console.Write(string.Concat(result.Select(o => o.ToString())));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜