Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single character from a char* in C

Tags:

c

string

char

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";
like image 453
Vivek Avatar asked Aug 12 '11 13:08

Vivek


2 Answers

Another way:

char * i;

for (i=a; *i; i++) {
   // i points successively to a[0], a[1], ... until a '\0' is observed.
}
like image 75
glglgl Avatar answered Sep 20 '22 09:09

glglgl


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

like image 38
MGZero Avatar answered Sep 23 '22 09:09

MGZero