Check if a string can be represented as ASCII


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Determines whether the argument string can be represented with the ASCII (<see cref="Encoding.ASCII"/>) encoding.
  3. /// </summary>
  4. /// <param name="value">The value to check.</param>
  5. /// <returns>
  6. /// <c>true</c> if the specified value is ASCII; otherwise, <c>false</c>.
  7. /// </returns>
  8. public static bool IsASCII(this string value)
  9. {
  10. // ASCII encoding replaces non-ascii with question marks, so we use UTF8 to see if multi-byte sequences are there
  11. return Encoding.UTF8.GetByteCount(value) == value.Length;
  12. }
  13.  
  14. [TestMethod]
  15. public void IsASCII_SimplestValid_ReturnsTrue()
  16. {
  17. string value = Encoding.ASCII.GetString(new byte[0]);
  18. var expected = true;
  19.  
  20. var actual = value.IsASCII();
  21.  
  22. Assert.AreEqual(expected, actual);
  23. }
  24.  
  25. [TestMethod]
  26. public void IsASCII_MultiByteValid_ReturnsTrue()
  27. {
  28. string value = "\0\0";
  29. var expected = true;
  30.  
  31. var actual = value.IsASCII();
  32.  
  33. Assert.AreEqual(expected, actual);
  34. }
  35.  
  36. [TestMethod]
  37. public void IsASCII_UnicodeInput_ReturnsFalse()
  38. {
  39. string value = "Ä€"; // first multibyte utf8 char
  40. var expected = false;
  41.  
  42. var actual = value.IsASCII();
  43.  
  44. Assert.AreEqual(expected, actual);
  45. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.