Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace StringVerification
- {
- public static class IsbnVerifier
- {
- /// <summary>
- /// Verifies if the string representation of number is a valid ISBN-10 identification number of book.
- /// </summary>
- /// <param name="number">The string representation of book's number.</param>
- /// <returns>true if number is a valid ISBN-10 identification number of book, false otherwise.</returns>
- /// <exception cref="ArgumentException">Thrown if number is null or empty or whitespace.</exception>
- public static bool IsValid(string number)
- {
- if (string.IsNullOrWhiteSpace(number))
- {
- throw new ArgumentException("The number is null, empty or whitespace", nameof(number));
- }
- if (number.Length < 10 || number.Length > 13)
- {
- return false;
- }
- if (CharToInt(number[0]) == -1 || CharToInt(number[0]) == 10)
- {
- return false;
- }
- int checkSum = CharToInt(number[0]) * 10;
- byte hyphenCount = 0;
- if (number[1] == '-')
- {
- hyphenCount++;
- }
- for (int i = 1 + hyphenCount; i < 4 + hyphenCount; i++)
- {
- if (CharToInt(number[i]) == -1 || CharToInt(number[i]) == 10)
- {
- return false;
- }
- checkSum += CharToInt(number[i]) * (10 - i + hyphenCount);
- }
- if (number[4 + hyphenCount] == '-')
- {
- hyphenCount++;
- }
- for (int i = 4 + hyphenCount; i < number.Length - 2; i++)
- {
- if (CharToInt(number[i]) == -1 || CharToInt(number[i]) == 10)
- {
- return false;
- }
- checkSum += CharToInt(number[i]) * (10 - i + hyphenCount);
- }
- if (CharToInt(number[^1]) == -1 || CharToInt(number[^2]) == 10)
- {
- return false;
- }
- if (number[^2] == '-')
- {
- checkSum += CharToInt(number[^1]);
- }
- else
- {
- checkSum += CharToInt(number[^1]) + (CharToInt(number[^2]) * 2);
- }
- return checkSum % 11 == 0;
- }
- private static int CharToInt(char digit) =>
- digit switch
- {
- '0' => 0,
- '1' => 1,
- '2' => 2,
- '3' => 3,
- '4' => 4,
- '5' => 5,
- '6' => 6,
- '7' => 7,
- '8' => 8,
- '9' => 9,
- 'X' => 10,
- _ => -1
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement