You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
But this compiles down to:
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied by the resulting String.
String.valueOf(char) "gets in the back door" by wrapping the char in a single-element array and passing it to the package private constructor String(char[], boolean), which avoids the array copy.
You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
But this compiles down to:
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied by the resulting String.
String.valueOf(char) "gets in the back door" by wrapping the char in a single-element array and passing it to the package private constructor String(char[], boolean), which avoids the array copy.
I've got of the following five six methods to do it.
// Method #1
String stringValueOf = String.valueOf('c'); // most efficient
// Method #2
String stringValueOfCharArray = String.valueOf(new char[]{x});
// Method #3
String characterToString = Character.toString('c');
// Method #4
String characterObjectToString = new Character('c').toString();
// Method #5
// Although this approach seems very simple,
// this is less efficient because the concatenation
// expands to a StringBuilder.
String concatBlankString = 'c' + "";
// Method #6
String fromCharArray = new String(new char[]{x});
Note: Character.toString(char) returns String.valueOf(char). So effectively both are same.
String.valueOf(char[] value) invokes new String(char[] value), which in turn sets the value char array.
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
On the other hand String.valueOf(char value) invokes the following package private constructor.
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
Source code from String.java in Java 8 source code
Hence
String.valueOf(char)seems to be most efficient method, in terms of both memory and speed, for convertingchartoString.
Sources:
- How to convert primitive char to String in Java
- How to convert Char to String in Java with Example
How to convert string to char array in C++? - Stack Overflow
how to convert char * to string
How do I convert a char to String?
A Simpler Way to Convert a String to char*?
Videos
The string class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
Another solution might look like this,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
Simplest way I can think of doing it is:
string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());
For safety, you might prefer:
string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
or could be in this fashion:
string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());
Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;
A constant char array is good enough for you so you go with,
const char *array = tmp.c_str();Or you need to modify the char array so constant is not ok, then just go with this
char *array = &tmp[0];
Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.
Unfortunately for C++ programmers all over the world, there doesn't exist a std::string constructor that simply takes a char, so you're not able to do something like std::string test('A') (does anyone have an explication for this?).
Of course, this leads to super frustrating / non-intuitive behavior and introduces tons of hidden bugs, but it is what it is.
However, I recently discovered the following code snippets, and for the life of me I cannot understand why this works this way, and I was wondering if someone could explain the rationale behind this (tested of both gcc and clang).
If you write :
std::string test = "STRING"; std::string test2 = test[0];
You, (of course, anyone would have guessed I'm sure) get a compilation error, because test[0] returns a char which cannot be converted to a string.
However, if you write :
std::string test = "STRING"; test = test[0];
I would expect the same result, because, well, you're still trying to convert a char to a string. However, to my surprise, this actually compiles and works exactly the way you would expect (test == "S").
Could anyone explains this...?
As a beginner with code, I'm trying to create a simple console Hangman game.
I think what I want to do is convert the user's word to a character array, which I do using:
char[] answerArray = word.ToCharArray();
Once it's into the array though, I can't get it to display in a single line again?
If I use:
Console.WriteLine(answerArray.ToString);
It shows every character as "System.Char[]".
The best I can figure out is:
Console.WriteLine("{0} {1} {2}..." , answerArray[0], answerArray[1], answerArray[2]...);It seems that this has to be hardcoded this way though, and an undefined reference in Console.WriteLine causes an exception, which means I have to specify a word with a certain number of characters, otherwise the program will crash.
I've seen pages on stackoverflow and other sites saying to use a foreach loop but that is still giving me each letter on a separate line.
Thanks for any help!
I need to compile shaders for OpenGL and I need to provide "shaderSource" for that, shaderSource must be char*, but I made a function that reads file contents into a variable, but that variable is an std::string, and I can't convert an std::strings to a char* with (char*), so I made this function
char* FileToChrP(const std::string& FileName) {
std::ifstream file(FileName, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
throw std::runtime_error("Your file is cooked twin | FileToChrP");
}
std::streamsize size = file.tellg();
if (size < 0) throw std::runtime_error("Ur file is cooked twin | FileToChrP");
file.seekg(0, std::ios::beg);
char* buffer = new char[size + 1];
file.read(buffer, size);
buffer[size] = '\0';
return buffer;
}char* FileToChrP(const std::string& FileName) {
std::ifstream file(FileName, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
throw std::runtime_error("Your file is cooked twin | FileToChrP");
}
std::streamsize size = file.tellg();
if (size < 0) throw std::runtime_error("Ur file is cooked twin | FileToChrP");
file.seekg(0, std::ios::beg);
char* buffer = new char[size + 1];
file.read(buffer, size);
buffer[size] = '\0';
return buffer;
}
but there's a problem, i have to manually delete the buffer with delete[] buffer and that feels wrong.
Also, this seems like a thing that c++ would already have. Is there abetter solution?