How to convert char to string

i have an input buffer as a CHAR * variable, but would like to convert that to a STRING variable. For me its easier to handle the string manipulations with the given string functions…

Could not find anything in the docs or the discussion forums.

I know there must be a trivial way to do this.

thx

KW

You could give this a try: http://www.dotnetperls.com/convert-char-array-string

Have you tried assigning the char* variable to the String?

There is an overload String & operator = (const char *cstr);, so this should work:

    char cStr[10] = "Test";  // this way cStr is of type char*
    String sStr = cStr; 
2 Likes

yes thanks that is it

I guess this does not copy, but the char / string accesses the same memory cells?

[EDIT] works perfectly, thanks

KW

No, it actually does copy the characters to a new location on the heap.

Look at the implementation of the assignment operator (you find this in the open source section)

String & String::copy(const char *cstr, unsigned int length)
{
	if (!reserve(length)) {
		invalidate();
		return *this;
	}
	len = length;
	strcpy(buffer, cstr);
	return *this;
}
...
String & String::operator = (const char *cstr)
{
	if (cstr) copy(cstr, strlen(cstr));
	else invalidate();
	
	return *this;
}
2 Likes