C语言 如何迭代C中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3213827/
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
How to iterate over a string in C?
提问by Vincent
Right now I'm trying this:
现在我正在尝试这个:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s %s sourcecode input", argv[0], argv[1]);
}
else {
char source[] = "This is an example.";
int i;
for (i = 0; i < sizeof(source); i++) {
printf("%c", source[i]);
}
}
getchar();
return 0;
}
This does also NOT work:
这也不起作用:
char *source = "This is an example.";
int i;
for (i = 0; i < strlen(source); i++){
printf("%c", source[i]);
}
I get the error
我收到错误
Unhandled exception at 0x5bf714cf (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation while reading at position 0x00000054.
Test.exe 中 0x5bf714cf (msvcr100d.dll) 处未处理的异常:0xC0000005:在位置 0x00000054 读取时发生访问冲突。
(loosely translated from german)
(从德语粗略翻译)
So what's wrong with my code?
那么我的代码有什么问题?
回答by
You want:
你要:
for (i = 0; i < strlen(source); i++){
sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:
sizeof 为您提供指针的大小,而不是字符串。但是,如果您将指针声明为数组,它会起作用:
char source[] = "This is an example.";
but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:
但是如果你将数组传递给函数,它也会衰减为一个指针。对于字符串,最好始终使用 strlen。并注意其他人所说的将 printf 更改为使用 %c 的内容。而且,考虑到 mmyers 对效率的评论,最好将对 strlen 的调用移出循环:
int len = strlen( source );
for (i = 0; i < len; i++){
or rewrite the loop:
或重写循环:
for (i = 0; source[i] != 0; i++){
回答by Alexandre C.
One common idiom is:
一种常见的成语是:
char* c = source;
while (*c) putchar(*c++);
A few notes:
一些注意事项:
- In C, strings are null-terminated. You iterate while the read character is not the null character.
*c++incrementscand returns the dereferenced oldvalue ofc.printf("%s")prints a null-terminated string, not a char. This is the cause of your access violation.
- 在 C 中,字符串是以空字符结尾的。在读取字符不是空字符时进行迭代。
*c++递增c并返回取消引用的旧值c。printf("%s")打印一个以空字符结尾的字符串,而不是一个字符。这是您访问冲突的原因。
回答by Mark Ingram
Rather than use strlen as suggested above, you can just check for the NULL character:
您可以只检查 NULL 字符,而不是像上面建议的那样使用 strlen:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char *const pszSource = "This is an example.";
const char *pszChar = pszSource;
while (pszChar != NULL && *pszChar != ' #include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char *source = "This is an example.";
int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
for (int i = 0; i < length; i++)
{
printf("%c", source[i]);
}
}
')
{
printf("%s", *pszChar);
++pszChar;
}
getchar();
return 0;
}
回答by KenE
- sizeof() includes the terminating null character. You should use strlen() (but put the call outside the loop and save it in a variable), but that's probably not what's causing the exception.
- you should use "%c", not "%s" in printf - you are printing a character, not a string.
- sizeof() 包括终止空字符。您应该使用 strlen() (但将调用放在循环之外并将其保存在变量中),但这可能不是导致异常的原因。
- 你应该在 printf 中使用“%c”,而不是“%s”——你打印的是一个字符,而不是一个字符串。
回答by Prasoon Saurav
This should work
这应该工作
char *source = "This is an example.";
int i;
for (i = 0; i < strlen(source); i++){
printf("%c", source[i]);
}
回答by Jacob
sizeof(source)returns the number of bytes required by the pointer char*. You should replace it with strlen(source)which will be the length of the string you're trying to display.
sizeof(source)返回指针所需的字节数char*。您应该将其替换strlen(source)为您要显示的字符串的长度。
Also, you should probably replace printf("%s",source[i])with printf("%c",source[i])since you're displaying a character.
此外,您可能应该替换为printf("%s",source[i]),printf("%c",source[i])因为您正在显示一个字符。
回答by JSB????
sizeof(source)is returning to you the size of achar*, not the length of the string. You should be usingstrlen(source), and you should move that out of the loop, or else you'll be recalculating the size of the string every loop.- By printing with the
%sformat modifier,printfis looking for achar*, but you're actually passing achar. You should use the%cmodifier.
sizeof(source)返回给你 a 的大小char*,而不是字符串的长度。您应该使用strlen(source),并且应该将其移出循环,否则您将在每个循环中重新计算字符串的大小。- 通过使用
%s格式修饰符打印,printf正在寻找 achar*,但实际上您传递的是char. 您应该使用%c修饰符。
回答by Pablo Santa Cruz
Just change sizeof with strlen.
只需使用 strlen 更改 sizeof 即可。
Like this:
像这样:
printf("%s", source + i);
回答by Keith Randall
Replace sizeof with strlen and it should work.
用 strlen 替换 sizeof ,它应该可以工作。
回答by ULysses
You need a pointer to the first char to have an ANSI string.
您需要一个指向第一个字符的指针才能获得 ANSI 字符串。
##代码##will do the job
会做这份工作
Plus, of course you should have meant strlen(source), not sizeof(source).
另外,您当然应该指的是strlen(source),而不是sizeof(source)。

