Get one character from char * in C

Is there a way to move a character by character or extract a single character from char * in C?

Consider the following code. Now, which of the best ways to get individual characters? Suggest me a method without using any string functions.

char *a = "STRING"; 
+6
source share
5 answers

Another way:

 char * i; for (i=a; *i; i++) { // i points successively to a[0], a[1], ... until a '\0' is observed. } 
+19
source
 size_t i; for (i=0; a[i]; i++) { /* do something with a[i] */ } 
+4
source

Knowing the length of the char array, you can loop through it with a for loop.

 for (int i = 0; i < myStringLen; i++) { if (a[i] == someChar) //do something } 

Remember that 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: since I was asked for comments, see section 5.3.2 of this link for more information on arrays and pointers: http://publications.gbdirect.co.uk/c_book/chapter5/pointers.html

+4
source

Like this.

 char a1[] = "STRING"; const char * a2 = "STRING"; char * c; /* or "const char" for a2 */ for (c = aN; *c; ++c) { /* *c is the character */ } 

Here N may be 1 or 2 . For a1 you can change the characters, for a2 you cannot. Note that assigning a string literal to char* not recommended.

+3
source
 int i=0; while(a[i]!=0)/* or a[i]!='\0' */ { // do something to a[i] ++i; } 

EDIT:

You can also use strlen(a) to get the number of characters in a .

+2
source

Source: https://habr.com/ru/post/894914/


All Articles