Skip to content

Commit

Permalink
Merge pull request #51 from snowfrogdev/pvaillancourt/is-acii
Browse files Browse the repository at this point in the history
Add an IsAscii extension method for string
  • Loading branch information
ardalis authored Aug 10, 2022
2 parents 757a584 + 0817ca6 commit 6e39bba
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,6 @@ MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/

# Visual Studio Code configuration files
.vscode
36 changes: 36 additions & 0 deletions src/Ardalis.Extensions/StringManipulation/IsAscii.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Linq;

namespace Ardalis.Extensions.StringManipulation;

public static partial class StringManipulationExtensions
{
/// <summary>
/// Checks if all characters in this string are within the ASCII range.
/// </summary>
/// <example>
/// <code>
/// var ascii = "hello!\n";
/// var nonAscii = "Grüße, Jürgen ❤";
///
/// Assert.True(ascii.IsAscii());
/// Assert.False(nonAscii.IsAscii());
/// </code>
/// </example>
public static bool IsAscii(this string text)
{
return text.ToCharArray().All(c => IsAscii(c));
}


// Return true for all characters below or equal U+007f, which is ASCII.

/// <summary>
/// Returns <see langword="true"/> if <paramref name="c"/> is an ASCII
/// character ([ U+0000..U+007F ]).
/// </summary>
/// <remarks>
/// Per http://www.unicode.org/glossary/#ASCII, ASCII is only U+0000..U+007F.
/// </remarks>
private static bool IsAscii(char c) => (uint)c <= '\x007F';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Ardalis.Extensions.StringManipulation;
using Xunit;

namespace Ardalis.Extensions.UnitTests.StringManipulation;

public class IsAsciiTests
{
[Theory]
[InlineData("", true)]
[InlineData("Hello!\n", true)]
[InlineData("banana\0\x7F", true)]
[InlineData("Vi\xe1\xbb\x87t Nam", false)]
[InlineData("ประเทศไทย中华Việt Nam", false)]
[InlineData("Grüße, Jürgen ❤", false)]
public void ValidatesIfStringIsAscii(string input, bool expected)
{
Assert.Equal(expected, input.IsAscii());
}
}

0 comments on commit 6e39bba

Please sign in to comment.