toggleCase() for Narrow String
Salih Dincer
salihdb at hotmail.com
Sun Apr 13 17:28:12 UTC 2025
Hi,
Please watch: https://youtu.be/siw602gzPaU
If he had learned this method like me, he would not have needed
if's and long explanations. :)
It's a very redundant thing (ASCII magic) that also weeds out the
incompatible character set. This approach adopts the toggle/flip
method through XOR rather than toLower/toUpper:
```d
import std.traits : isNarrowString;
bool isAsciiString(T)(T str)
if (isNarrowString!T)
{
import std.uni : byGrapheme;
auto range = str.byGrapheme;
import std.range : walkLength;
return range.walkLength == str.length;
}
auto toggleCase(T)(T str)
in (str.isAsciiString, "Incompatible character set!")
{
auto ret = str.dup;
foreach (ref chr; ret) {
chr ^= ' '; // toggle character
}
return ret;
}
import std.stdio;
void main()
{
string test = "dlANG"; // "ḍlANG";
test.toggleCase().writeln(); // "DLang"
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list