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

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

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

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

并且最好只对指针使用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); } 

测试 。

使用指数:

 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]); } 

测试 。

将此视为对Dukeling给出的答案的扩展

当你使用

 char *quote = "Hello World"; 

这使得只读字符串意味着您无法以更简单的方式更改其内容。

 Here *quote points to 'H' BUT, you cannot do *quote = 'A'; This will give you an error. 

如果您希望更改字符串中的字符,使用数组是一个好习惯。

 char quote[] = "Hello World"; Here also *quote points to 'H' BUT, in this case *quote = 'A' is perfectly valid. The array quote will get changed. 

您在初始化程序中重新分配quote ,该quote无效且会导致访问冲突,因为您在*quote != NULL部分中取消引用它。

语义上的NULL'\0'是等价的,但从语法上来说我更喜欢这个。 请注意,通过使用此方法,您可以保留指向字符串(的开头)的指针。

 wchar const_t* quote = L"To be or not to be, that is the question."; for( wchar_t* c = quote; *c != '\0'; c++ ) { *c = tolower( *c ); } 

或者使用索引:

 wchar const_t quote[] = L"To be or not to be, that is the question."; for( size_t i = 0; i < sizeof(quote); i++ ) { quote[i] = tolower( quote[i] ); } 

(请注意,如果在编译时不知道quote的值,那么sizeof的语义将会改变)