digitalmars.D.learn - How to covert dchar and wchar to string?
- Rempas (3/3) Jan 25 2021 Actually what the title says. For example I have dchar c =
- Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= (18/21) Jan 25 2021 if you are trying to avoid GC allocations this is not what you
- Q. Schroll (17/20) Jan 25 2021 char[] dcharToChars(char[] buffer, dchar value)
- Steven Schveighoffer (9/12) Jan 26 2021 That's EXACTLY what you want to use, if what you want is a string.
Actually what the title says. For example I have dchar c = '\u03B3'; and I want to make it into string. I don't want to use "to!string(c);". Any help?
Jan 25 2021
On Monday, 25 January 2021 at 18:45:11 UTC, Rempas wrote:Actually what the title says. For example I have dchar c = '\u03B3'; and I want to make it into string. I don't want to use "to!string(c);". Any help?if you are trying to avoid GC allocations this is not what you want. dchar c = '\u03B3'; string s = ""; s ~= c; writeln(s); writeln(s.length); // please aware of this Some useful things: string is immutable(char)[] wstring is immutable(wchar)[] dstring is immutable(dchar)[] if you have a char[]: you can convert it to a string using assumeUnique: import std.exception: assumeUnique; char[] ca = ... string str = assumeUnique(ca); // similar for dchar->dstring and wchar->wstring
Jan 25 2021
On Monday, 25 January 2021 at 18:45:11 UTC, Rempas wrote:Actually what the title says. For example I have dchar c = '\u03B3'; and I want to make it into string. I don't want to use "to!string(c);". Any help?char[] dcharToChars(char[] buffer, dchar value) { import std.range : put; auto backup = buffer; put(buffer, value); return backup[0 .. $ - buffer.length]; } void main() { dchar c = '\u03B3'; char[4] buffer; char[] protoString = dcharToChars(buffer, c); import std.stdio; writeln("'", protoString, "'"); } Unfortunately, `put` is not nogc in this case.
Jan 25 2021
On 1/25/21 1:45 PM, Rempas wrote:Actually what the title says. For example I have dchar c = '\u03B3'; and I want to make it into string. I don't want to use "to!string(c);". Any help?That's EXACTLY what you want to use, if what you want is a string. If you just want a conversion to a char array, use encode [1]: import std.utf; char[4] buf; size_t nbytes = encode(buf, c); // now buf[0 .. nbytes] contains the char data representing c -Steve [1] https://dlang.org/phobos/std_utf.html#encode
Jan 26 2021