Reputation: 3077
I'm currently using
char *thisvar = "stringcontenthere";
to declare a string in C.
Is this the best way to declare a string in C?
And how about generating a C-String from C++-Strings?
Upvotes: 11
Views: 30084
Reputation: 4166
In C it depends on how you'll use the string:
char* str = "string";
method is ok (but should be char const*
)char str[] = "string";
char* str = strdup("string");
, and make sure it gets free
d eventually.if this doesnt cover it, try adding more detail to your answer.
Upvotes: 16
Reputation: 8818
It depends. For ASCII encoded strings see paragraphs C and C++. For unicode encoded strings see last paragraph.
As David pointed out it depends on how to use the string in C:
const char s[] = "Hello World";
char s[] = "Hello World";
char *data
; Initialization then should be customized.Please note in C there are all Strings Null-terminated, that means the definition of e.g. char s[] = "foo";
implicitly includes a NULL
character at the end s[3]='\0'
.
Also please note the subtile difference between char *s
and char s[]
which might often behave the same but sometimes not! (see Is an array name a pointer?) for example:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char* argv[])
{
char s[] = "123456789123456789123456789";
char *t = (char*) malloc( sizeof(char) * 28 );
for( size_t i = 0; i < 28; ++i )
t[ i ] = 'j';
printf( "%lu\n", sizeof(s) );
printf( "%lu\n", sizeof(t) );
printf( "%s\n", s );
printf( "%s\n", t );
return EXIT_SUCCESS;
}
So I recommend to use char arrays whenever you use them as strings and char pointers whenever you use them as data array.
In C++ there is an own string data type: std::string
. If you just need to have a C-String version of a std::string (e.g. using some C-API) just use the c_str()
member:
std::string s = "Hello World";
your_c_call( s.c_str(), ... );
I you want to have unicode strings then you should really go with something like
char utf8String[] = u8"Hello World";
and try not to use wchar_t
whenever possible. See this excellent article on that issue: http://www.nubaria.com/en/blog/?p=289. Please not that there is also unicode support for C++. But generally I am tempted to say that you should go with normal characters as far as you can. Interesting resource on that: http://www.cprogramming.com/tutorial/unicode.html
Upvotes: 1
Reputation: 55726
As other suggested, and I you want to "do it" the C++
way, use a std::string
.
If you somehow need a C-string
, std::string
has a method that gives a const char*
.
Here is an example:
#include <iostream>
#include <string>
void dummyFunction(const char* str)
{
// Do something
}
int main(int, char**)
{
std::string str = "hello world!";
dummyFunction(str.c_str());
return EXIT_SUCCESS;
}
Upvotes: 1
Reputation: 116246
Is this C or C++? In C++ you should use std::string
:
std::string aString("stringcontenthere");
Upvotes: 0