Working with C-Strings
To wrap up this section, let’s look at how strings works. While many of these features are likely to be handled by the language and its libraries, knowing how this works will help you understand what is happening when you perform operations with text. Many of these operations are time-consuming as you are working with arrays, so understanding their operations can help you optimise your code, thereby improving its speed and efficiency.
As you will recall, strings are just character arrays with a null terminator to mark the end of the string. Using this knowledge, let’s think about how a function like SplashKit’s write_line
might work. We could code something like this ourselves in a program using the following steps:
- Step 1: We allocate a block of memory to store the string
- Step 2: We assign the string literal “Hello” to the string my_string (note that string literals automatically add a null terminator)
- Step 3: We print the string to the terminal by looping through the array until we reach the null terminator, and printing each character.
This is how the string function operate. Notice that we have two parts to the condition in the for loop, my_string[i] != '\0'
is looking to end when the null terminator is encountered while i < MAX_STRING_LENGTH
is making sure we do not got past the end of the string.
String concatenation
There are many actions that you can perform with arrays, but let’s have a look at how something like string concatenation would work. In C there are a whole range of functions to manipulate c-strings, but it is good to think about how they work.
The above program looks simple right? It looks as though we simply take the two character arrays and create the final result “John Smith”, and indeed it’s a common operation when working with strings to concatenate them - but there’s a catch. We aren’t including using a string data type, and we can’t simply add two arrays together, or string literals and character arrays.
The way to concatenate two strings in C without any libraries is quite simple, and entails looping through the first string, and copying each character into the new string, and then looping through the second string and copying each character into the new string. Let’s take a look at how we can manually concatenate two names together (with a space in between):
This kind of thinking is needed whenever you want to concatenate any arrays, no matter what data they contain.