What I want to do is to iterate through the quote till the end of the quote/(*quote has nothing in it). Is my code valid?
char *quote = "To be or not to be, that is the question.";
for (quote = 0; *quote != NULL; quote++){
*quote = tolower(*quote);
}
For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. String s = "example"; // loop through the string from 0 to length for(int i=0; i < s. length(); i++) { String ithLetter = s.
So, the expression *p in loop just check that the decimal equivalent of character at the memory address pointed by p is either a zero or non-zero. When p reaches the end of the string and finds the first '\0' character, the expression *p returns1 a zero value. A zero means false in C.
You probably need another pointer to traverse the array, otherwise access to your original string will be lost.
And preferably only use NULL
for pointers.
Don't use 0
as the initial value, unless you want to use indices instead (see below).
Doing char *quote =
will simply make quote
point to the read-only literal, instead of copying the string. Use char quote[] =
instead.
char quote[] = "To be or not to be, that is the question.";
char *quotePtr;
for (quotePtr = quote; *quotePtr != '\0'; quotePtr++){
*quotePtr = tolower(*quotePtr);
}
Test.
Using indices:
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.
Consider this as an expansion to the answer given by Dukeling
When you use
char *quote = "Hello World";
This makes a read-only string, means that you can't change its contents in a simpler way.
Here *quote points to 'H'
BUT, you cannot do *quote = 'A';
This will give you an error.
If you wish to make changes to the characters in a string, it is a good habit to use arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With