Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to character array in c (or) how to extract a single char form string?

Tags:

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?

like image 561
Cute Avatar asked May 15 '09 10:05

Cute


People also ask

Can you convert string to char array?

char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.

Can you convert a string to a char in C?

The c_str() and strcpy() function in C++C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

How do I convert a string to an array of one string?

Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.


2 Answers

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

like image 75
David Oakley Avatar answered Nov 02 '22 05:11

David Oakley


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]...).

like image 36
alamar Avatar answered Nov 02 '22 05:11

alamar