Thread overview
toggleCase() for Narrow String
5 days ago
Salih Dincer
5 days ago
Paul Backus
5 days ago
Salih Dincer
5 days ago

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:

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

5 days ago

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!
5 days ago

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?

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