如何遍历由指针创建的字符串

Luc*_*Luo 5 c string pointers loops

我想要做的是遍历报价直到报价结束/(*报价中没有任何内容).我的代码有效吗?

char *quote = "To be or not to be, that is the question.";
for (quote = 0; *quote != NULL; quote++){
*quote = tolower(*quote);
}
Run Code Online (Sandbox Code Playgroud)

Duk*_*ing 11

您可能需要另一个指针来遍历数组,否则将丢失对原始字符串的访问.

并且最好仅NULL用于指针.

不要0用作初始值,除非你想使用索引(见下文).

这样做char *quote =只会quote指向只读文字,而不是复制字符串.请char quote[] =改用.

char quote[] = "To be or not to be, that is the question.";
char *quotePtr;
for (quotePtr = quote; *quotePtr != '\0'; quotePtr++){
  *quotePtr = tolower(*quotePtr);
}
Run Code Online (Sandbox Code Playgroud)

试验.

使用指数:

char quote[] = "To be or not to be, that is the question.";
int i;
for (i = 0; quote[i] != '\0'; i++){
  quote[i] = tolower(quote[i]);
}
Run Code Online (Sandbox Code Playgroud)

试验.