char []和C中的字符串之间的区别 [英] Difference between char[] and strings in C
问题描述
C编程语言通过以下方式使用引号将字符常量与字符串常量区分开:
The C programming language distinguishes character constants from string constants by using quotation marks in the following manner:
'c'
是字符c,而"c"
是长度为1的字符串,由单个字符c组成.
'c'
is the character c, while "c"
is a string of length 1 consisting of the single character c.
为什么要区分?有什么用?这与C ++有何不同?
Why is this distinction made? How is it useful? How is this different from C++?
推荐答案
C 是[相对]低级别的静态类型编程语言.
C is [relatively] low-level statically typed programming language.
char c = 'c';
const char* s = "s";
以上语句不仅在字面常量的值(c:单字节存储; s:两个字节存储+ 4/8字节指针)上有所不同,而且在变量类型上(c:单字节,某些算术运算; s:4/8字节指针,不同的算术.)
The statements above differ not only in the value of the literal constant (c: single byte storage; s: two bytes storage + 4/8 byte pointer), but also in the type of variables (c: single byte, certain arithmetic ops; s: 4/8 byte pointer, different arithmetic).
我向你提出,后者的差异更为重要;使用文字常量可以更轻松地使用变量,函数参数,结构成员等.
I posit to you that the latter difference is more important; Literal constants are there to make use of variables, function arguments, struct members, etc easier.
此外,C语言中解决的典型问题具有低级性质,您可能会对单个字符和字符串之间的逻辑差异感兴趣.例如gpio,串行端口,子字符串搜索算法.
Furthermore, the typical problems solved in C are of low-level nature where you are interested in logical difference between single character and a string. For example gpio, serial port, substring search algorithm.
[当然,C也用于其他领域,在 glib
或 enlightenment
之类的更高级别的项目中,您不太可能看到太多的字符与字符串区别.]
[Of course C is also used in other domains, you are not likely to see much character vs string distinction in higher-level projects like glib
or enlightenment
.]
Python 是一种高级动态语言.
Python is a high-level dynamic language.
c = 'c'
s = "s"
在以上本地/标签 c
和 s
语句中,它们指向对象,并且类型是在运行时动态确定的.因此,根本不需要区分字符"和字符串".
In the statements above locals/labels c
and s
point to objects and type is determined at runtime, dynamically. Thus a distinction between a "character" and "string" is simply not needed.
用Python解决的问题通常要高得多,通常您需要处理JSON Blob,HTTP请求,数据库查询,虚拟机等;即使您需要处理单个字符,也可以使用length-1字符串作为近似值.
Problems solved in Python are usually of much higher level, typically you'd deal with JSON blobs, HTTP requests, database queries, virtual machines, etc; Even if you need to deal with single characters, length-1 string is an acceptable approximation.
[如果使用 numpy
或 cffi
,则您将担心字符和字符串的存储,而那些模块提供了这样做的机制.]
[If you used numpy
or cffi
, you would worry about storage of characters and strings and those modules provide mechanism to do so.]
这篇关于char []和C中的字符串之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!