Is there a way to traverse character by character or extract a single character from char* in C?
Consider the following code. Now which is the best way to get individual characters? Suggest me a method without using any string functions.
char *a = "STRING";
Another way:
char * i;
for (i=a; *i; i++) {
// i points successively to a[0], a[1], ... until a '\0' is observed.
}
Knowing the length of the char array, you can cycle through it with a for loop.
for (int i = 0; i < myStringLen; i++)
{
if (a[i] == someChar)
//do something
}
Remember, a char * can be used as a C-Style string. And a string is just an array of characters, so you can just index it.
EDIT: Because I was asked on the comments, see section 5.3.2 of this link for details on arrays and pointers: http://publications.gbdirect.co.uk/c_book/chapter5/pointers.html
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