I am trying to convert two or more chars into a single string. Is this possible, and if so, how might I go about this? (BTW I am new to programming...)
2 Answers
Create an array of char, or a pointer to char with enough heap memory allocated using malloc
(remember strings require a termination character '\0'
, so are longer than their content by one character). Then you can assign to individual array elements. A few examples how one could use those:
char *str = (char*)malloc((LENGTH+1)*sizeof(char));
// now str can store up to LENGTH characters plus null terminator
// copy at most LENGTH characters of string plus null terminator
strncpy(str, "Jello World!", LENGTH+1);
OR
char str[LENGTH+1];
// now str can store up to LENGTH characters plus null terminator
// copy at most LENGTH characters of string plus null terminator
strncpy(str, "Jello World!", sizeof(str));
Then you can do things like
str[0] = 'H';
// Now it's "Hello World!"
str[5] = '\0';
// and now just "Hello"
The strncpy is just an example on how to copy strings into existing character arrays. You could probably go with str[0]
style, just don't forget the null terminator.
-
Thanks for the help! However, are you sure I need to include + 1 to the LENGTH? I understand your logic, but when I do so with a string of combined chars, for example, 'a' and 'b', the result "abl" is printed onto the screen whenever I print the string. However, if I do not add one to the LENGTH, the result of printing the string is the desired output, "ab". What is your explanation?– Jason_VCommented Feb 22, 2017 at 4:04
-
1A char array of LENGTH+1 characters can hold a string of LENGTH characters plus null terminator (that's the +1). If you get extra characters, you're placing the null terminator in the wrong place.– BlauelfCommented Feb 22, 2017 at 6:55
So remember a string is just an array of characters, and we can create an array by using char MyCoolString[i + 1]
, where i
is the amount of characters you want and the +1
is for the \0
you need for you computer to know where the string ends. Now using our new string, you can write a for loop
to copy characters from an old string, or use the following syntax if you know you'll always only use 2 specific characters: char MyCoolString[] = {FirstString[0], FirstString[3], '\0'};
But be sure to not forget the \0
, or your computer will probably have issues. Hope this helps and good luck with the rest of pset2!