Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a string created by pointer

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);
}
like image 685
Lucy Luo Avatar asked Sep 24 '13 23:09

Lucy Luo


People also ask

How do you run a loop through a string?

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.

Can we use pointer in loop in C?

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.


2 Answers

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.

like image 75
Bernhard Barker Avatar answered Oct 14 '22 06:10

Bernhard Barker


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.
like image 34
nikoo28 Avatar answered Oct 14 '22 08:10

nikoo28