从 char* 创建包含转义字符的 char
考虑以下 char* 示例:
char* s = "\n";
如何将其转换为表示换行符的单个字符,如下所示:
char c = '\n';
除了处理换行符之外,我还需要能够将前面带有转义字符的任何字符转换为 char。这怎么可能?
Consider the following char* example:
char* s = "\n";
How can this be converted into a single char that represents the new line character like so:
char c = '\n';
In addition to processing newlines I also need to be able to convert any character with an escape character preceeding it into a char. How is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
char c = *s;
有效。字符串中的
'\n'
在源码中只有两个字符:编译后是单个字符;对于所有其他转义字符也是如此。字符串
"fo\111\tar"
编译后有 7 个字符(源代码中可见的 6 个字符('f'
,'o'< /code>、
'\111'
、'\t'
、'a'
和'r'
) 和一个空终止符)。char c = *s;
works.The
'\n'
inside the string is only two characters in source form: after compiling it is a single character; the same for all other escape character.The string
"fo\111\tar"
, after compiling, has 7 characters (the 6 visible in the source code ('f'
,'o'
,'\111'
,'\t'
,'a'
, and'r'
) and a null terminator).取消引用它:
Dereference it:
正如其他人所说,换行符实际上只是内存中的一个字符。要从字符串指针获取单个字符,您可以像访问数组一样访问指针(当然,假设为指向的字符串分配了内存):
As others said, the newline is actually only one character in memory. To get a single character from a string pointer, you can access your pointer as if it is an array (assuming, of course, that there is memory allocated for the string pointed to):
你的意思是这样的吗?
Do you mean something like that?