私がしたいのは、見積もりの終わり(*引用符に何も入っていない)まで見積もりを繰り返すことです。私のコードは有効ですか?ポインタで作成された文字列をループする方法
char *quote = "To be or not to be, that is the question.";
for (quote = 0; *quote != NULL; quote++){
*quote = tolower(*quote);
}
私がしたいのは、見積もりの終わり(*引用符に何も入っていない)まで見積もりを繰り返すことです。私のコードは有効ですか?ポインタで作成された文字列をループする方法
char *quote = "To be or not to be, that is the question.";
for (quote = 0; *quote != NULL; quote++){
*quote = tolower(*quote);
}
おそらく、配列を走査する別のポインタが必要です。そうしないと、元の文字列へのアクセスが失われます。
そして、好ましくはポインタとしてNULL
を使用してください。
代わりにインデックスを使用する場合を除き、0
を初期値として使用しないでください(下記参照)。
Doing 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);
}
Test。
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]);
}
Test:インデックスを使用
。
for
イニシャライザに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
のセマンティクスが変更されることに注意してください)答えは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 = 0'は間違っています。 – Zong
なぜ 'unsigned int'を使わないのですか? – Recker