从 char* 创建包含转义字符的 char

发布于 2024-11-07 12:51:10 字数 190 浏览 0 评论 0原文

考虑以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怪我鬧 2024-11-14 12:51:10

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).

一抹淡然 2024-11-14 12:51:10

取消引用它:

char* s = "\n";
char c = *s;

Dereference it:

char* s = "\n";
char c = *s;
我不在是我 2024-11-14 12:51:10

正如其他人所说,换行符实际上只是内存中的一个字符。要从字符串指针获取单个字符,您可以像访问数组一样访问指针(当然,假设为指向的字符串分配了内存):

char* s = "\n";
char  c = s[0];

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):

char* s = "\n";
char  c = s[0];
梦冥 2024-11-14 12:51:10

你的意思是这样的吗?

char * s = "\n";
char c = *s;

Do you mean something like that?

char * s = "\n";
char c = *s;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文