/ Published in: C#

Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <summary> /// Determines whether the argument string can be represented with the ASCII (<see cref="Encoding.ASCII"/>) encoding. /// </summary> /// <param name="value">The value to check.</param> /// <returns> /// <c>true</c> if the specified value is ASCII; otherwise, <c>false</c>. /// </returns> public static bool IsASCII(this string value) { // ASCII encoding replaces non-ascii with question marks, so we use UTF8 to see if multi-byte sequences are there return Encoding.UTF8.GetByteCount(value) == value.Length; } [TestMethod] public void IsASCII_SimplestValid_ReturnsTrue() { var expected = true; var actual = value.IsASCII(); Assert.AreEqual(expected, actual); } [TestMethod] public void IsASCII_MultiByteValid_ReturnsTrue() { string value = "\0\0"; var expected = true; var actual = value.IsASCII(); Assert.AreEqual(expected, actual); } [TestMethod] public void IsASCII_UnicodeInput_ReturnsFalse() { string value = "Ä€"; // first multibyte utf8 char var expected = false; var actual = value.IsASCII(); Assert.AreEqual(expected, actual); }
Comments
