Checking, whether string contains only ascii.
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Feb 22 11:43:00 PST 2017
On Wed, Feb 22, 2017 at 07:26:15PM +0000, berni via Digitalmars-d-learn wrote:
> In my program, I read a postscript file. Normal postscript files
> should only be composed of ascii characters, but one never knows what
> users give us. Therefore I'd like to make sure that the string the
> program read is only made up of ascii characters. This simplifies the
> code thereafter, because I then can assume, that codeunit==codepoint.
> Is there a simple way to do so?
[...]
Hmm... What about:
import std.range.primitives;
bool isAsciiOnly(R)(R input)
if (isInputRange!R && is(ElementType!R : dchar))
{
import std.algorithm.iteration : fold;
return input.fold!((a, b) => a && b < 0x80)(true);
}
unittest
{
assert(isAsciiOnly("abcdefg"));
assert(!isAsciiOnly("abcбвг"));
}
Basically, it iterates over the string / range of characters and checks
that every character is less than 0x80, since anything that's 0x80 or
greater cannot be ASCII.
T
--
INTEL = Only half of "intelligence".
More information about the Digitalmars-d-learn
mailing list