20

I need to convert a string to a char array in C; how can I do this?

Or at least, how can I extract single chars from a string incrementally?

hat
  • 781
  • 2
  • 14
  • 25
Cute
  • 13,643
  • 36
  • 96
  • 112

3 Answers3

26

In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,

char myString[] = "This is some text";

You can access any character as a simple char by using myString as an array, thus:

char myChar = myString[6];
printf("%c\n", myChar); // Prints s

Hope this helps! David

David Oakley
  • 408
  • 4
  • 8
4

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

alamar
  • 18,729
  • 4
  • 64
  • 97
3

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);
NKN
  • 6,482
  • 6
  • 36
  • 55
65656565656
  • 91
  • 1
  • 12