简体   繁体   English

如何在C中将字符串转换为char

[英]How to convert string to char in C

I'm writing a compiler in C and need to get the ASCII value of a character defined in a source code file. 我正在用C编写编译器,需要获取源代码文件中定义的字符的ASCII值。 For normal letters this is simple but is there any way to convert the string "\\n" to the ASCII number for '\\n' in C (needs to work on all characters)? 对于普通字母,这​​很简单,但有没有办法将字符串“\\ n”转换为C中“\\ n”的ASCII数字(需要处理所有字符)?

Cheers 干杯

If the string is one character long, you can just index it: 如果字符串长度为一个字符,则可以将其编入索引:

char *s = "\n";
int ascii = s[0];

However, if you are on a system where the character set used is not ASCII, the above will not give you an ASCII value. 但是,如果您使用的字符集不是ASCII,则上面的代码不会为您提供ASCII值。 If you need to make sure your code runs on such rare machines, you can build yourself an ASCII table and use that. 如果您需要确保您的代码在如此稀有的机器上运行,您可以自己构建一个ASCII表并使用它。

If on the other hand, you have two characters, ie, 另一方面,如果你有两个字符,即

char *s = "\\n";

then you can do something like this: 然后你可以做这样的事情:

char c;
c = s[0];
if (c == '\\') {
    c = s[1]; /* assume s is long enough */
    switch (c) {
        case 'n': return '\n'; break;
        case 't': return '\t'; break;
        ...
        default: return c;
    }
}

The above assumes that your current compiler knows what '\\n' means. 以上假设您当前的编译器知道'\\n'含义。 If it doesn't, then you can still do it. 如果没有,那么你仍然可以做到。 For finding out how to do so, and a fascinating story, see Reflections on Trusting Trust by Ken Thompson. 要了解如何这样做,以及一个引人入胜的故事,请参阅Ken Thompson的“ 信任信任思考”

I'm writing a compiler in C 我正在用C编写一个编译器

Probably not a good idea to do it all in raw C. It's far better to be using something like Bison to handle the initial parsing. 在原始C中完成所有操作可能不是一个好主意。使用像Bison这样的东西处理初始解析会好得多。

That said, the best way of handling \\* escapes is just to have a lookup table of what each escape turns into. 也就是说,处理\\*转义的最佳方法就是找到每个转义变成什么的查找表。

You will need to write your own parser/converter. 您需要编写自己的解析器/转换器。 The list of escape sequences can be found online in many places. 可以在许多地方在线找到转义序列列表。 Parsing C style syntax is extremely difficult, so you may also wish to check out existing free implementations such as Clang . 解析C样式语法非常困难,因此您可能还希望查看现有的免费实现,例如Clang

You will need to implement this yourself. 您需要自己实现。 The reason is that what you are doing is determined by the String literal syntax of the language that you are compiling ! 原因是你正在做的是由你正在编译的语言的String文字语法决定的 (The fact that your compiler is implemented in C is immaterial.) (您的编译器在C中实现的事实并不重要。)

There are conventional escape sequences for String literals that span multiple languages; 存在跨越多种语言的字符串文字的常规转义序列; eg \\n typically denotes the ASCII NewLine character. 例如\\n通常表示ASCII NewLine字符。 However, that doesn't mean that these conventions are appropriate for the language you are trying to compile. 但是,这并不意味着这些约定适合您尝试编译的语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM