Tuesday, January 31, 2012

Converting a String to Character Array

First of all, character arrays (char[]) are terminated by '\0'.
For illustration, visit  http://www.cplusplus.com/doc/tutorial/ntcs/ 

Why do we need this conversion?
Most of the commonly used functions accept char[] type instead of string as parameters.

  • strcpy()
  • strcmpi()
  • strtok()

So far, I have known two ways to convert a string to array of characters.
  1. copy()
  2. c_str()
I won't be discussing about copy() since this will require you to manually terminate the char[]. Meaning, you will have to determine where to put '\0' -usually right after the index of the last non-null element. To know more about this, you can visit
http://www.cplusplus.com/reference/string/string/copy/.

c_str() is easier to use because it automatically assigns '\0' after the last non-null element.


Syntax:
s.c_str() //s previously declared as string

Sample Program:
The program copies string s to char carr[].

strcpy() makes this type of copying possible, accepting two char[] as parameters.
The first is the destination char[] where the content is to be copied.
The second is the source, the char[] to be copied.

Since variable s is a string, we converted it to char[] by issuing s.c_str().

No comments:

Post a Comment