www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - toggleCase() for Narrow String

reply Salih Dincer <salihdb hotmail.com> writes:
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 79
Apr 13
next sibling parent Paul Backus <snarwin gmail.com> writes:
On Sunday, 13 April 2025 at 17:28:12 UTC, Salih Dincer wrote:
 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:
This is clever, but you are still missing something important. Take a look at this example: string test = "I love dlang!"; test.toggleCase().writeln(); // "iLOVEDLANG" - wrong!
Apr 13
prev sibling parent Salih Dincer <salihdb hotmail.com> writes:
On Sunday, 13 April 2025 at 17:28:12 UTC, Salih Dincer wrote:
 It's a very redundant thing (ASCII magic) that also weeds out 
 the incompatible character set.
Again and wgain opss! You can't get rid of if, but it's better with isAlpha(), like? ```d auto toggleCase(T)(T str) in (str.isAsciiString, "Incompatible character set!") { import std.ascii : isAlpha; auto ret = str.dup; foreach (ref chr; ret) { if (chr.isAlpha) { chr ^= ' '; // toggle character } } return ret; } unittest { string Aqw12 = `aQW 12`; assert(Aqw12.toggleCase() == "Aqw\n 12"); } ``` SDB 79
Apr 13