从C中的char *中获取单个字符

有没有办法逐个字符遍历或从C中的char *中提取单个字符?

请考虑以下代码。 现在哪个是获得个性化角色的最佳方式? 建议我不使用任何字符串函数的方法。

char *a = "STRING"; 

其他方式:

 char * i; for (i=a; *i; i++) { // i points successively to a[0], a[1], ... until a '\0' is observed. } 

知道了char数组的长度,你可以用for循环遍历它。

 for (int i = 0; i < myStringLen; i++) { if (a[i] == someChar) //do something } 

请记住,char *可以用作C风格的字符串。 字符串只是一个字符数组,因此您可以将其编入索引。

编辑:因为有人在评论时被问到,有关数组和指针的详细信息,请参阅此链接的第5.3.2节: http : //publications.gbdirect.co.uk/c_book/chapter5/pointers.html

 size_t i; for (i=0; a[i]; i++) { /* do something with a[i] */ } 

像这样。

 char a1[] = "STRING"; const char * a2 = "STRING"; char * c; /* or "const char" for a2 */ for (c = aN; *c; ++c) { /* *c is the character */ } 

这里N可以是12 。 对于a1您可以修改字符,对于a2则不能。 请注意,不建议将字符串文字指定给char*

 int i=0; while(a[i]!=0)/* or a[i]!='\0' */ { // do something to a[i] ++i; } 

编辑:

您还可以使用strlen(a)来获取a的字符数。