digitalmars.D.learn - toggleCase() for Narrow String
- Salih Dincer (34/34) Apr 13 Hi,
- Paul Backus (5/12) Apr 13 This is clever, but you are still missing something important.
- Salih Dincer (26/28) Apr 13 Again and wgain opss! You can't get rid of if, but it's better
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
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
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