www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to covert dchar and wchar to string?

reply Rempas <rempas tutanota.com> writes:
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
next sibling parent Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
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
prev sibling next sibling parent Q. Schroll <qs.il.paperinik gmail.com> writes:
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
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
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