C语言 从 C 中的 char* 获取单个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7040501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a single character from a char* in C
提问by Vivek
Is there a way to traverse character by character or extract a single character from char* in C?
有没有办法逐个字符地遍历或从 C 中的 char* 中提取单个字符?
Consider the following code. Now which is the best way to get individual characters? Suggest me a method without using any string functions.
考虑以下代码。现在哪个是获得单个角色的最佳方法?建议我一种不使用任何字符串函数的方法。
char *a = "STRING";
回答by glglgl
Another way:
其它的办法:
char * i;
for (i=a; *i; i++) {
// i points successively to a[0], a[1], ... until a 'for (int i = 0; i < myStringLen; i++)
{
if (a[i] == someChar)
//do something
}
' is observed.
}
回答by MGZero
Knowing the length of the char array, you can cycle through it with a for loop.
知道 char 数组的长度,您可以使用 for 循环遍历它。
size_t i;
for (i=0; a[i]; i++) {
/* do something with a[i] */
}
Remember, a char * can be used as a C-Style string. And a string is just an array of characters, so you can just index it.
请记住,char * 可以用作 C 样式字符串。一个字符串只是一个字符数组,所以你可以对它进行索引。
EDIT: Because I was asked on the comments, see section 5.3.2 of this link for details on arrays and pointers: http://publications.gbdirect.co.uk/c_book/chapter5/pointers.html
编辑:因为我被问及评论,有关数组和指针的详细信息,请参阅此链接的第 5.3.2 节:http: //publications.gbdirect.co.uk/c_book/chapter5/pointers.html
回答by R.. GitHub STOP HELPING ICE
char a1[] = "STRING";
const char * a2 = "STRING";
char * c; /* or "const char" for a2 */
for (c = aN; *c; ++c)
{
/* *c is the character */
}
回答by Kerrek SB
Like this.
像这样。
int i=0;
while(a[i]!=0)/* or a[i]!='##代码##' */
{
// do something to a[i]
++i;
}
Here Ncan be 1or 2. For a1you can modify the characters, for a2you cannot. Note that assigning a string literal to a char*is deprecated.
这里N可以是1或2。因为a1你可以修改字符,因为a2你不能。请注意,char*不推荐将字符串文字分配给 a 。
回答by Dan
EDIT:
编辑:
You can also use strlen(a)to get the number of characters in a.
您还可以使用strlen(a)来获取a.

