C Strings: The Basics of Creating, Using, and Updating Strings in C
In C, a string is defined as an array of characters. A string array will always terminate with a special character, “\0.” Strings are frequently used and manipulated in C as a way of storing and printing text. For example, a string might be a user name, a password, or an email address. This character array can be interacted with character by character.
Learning how to manipulate strings is one of the foundational skills of working with C. Strings can be collected from the user, printed to the console, and printed to files. They can be re-written in different orders (such as reversed), concatenated (added to), or cut (removed from). You can collect a string, store a string, or return a string.
Last Updated August 2019
Learn C in ten easy steps on Windows, Mac OS X or Linux | By Huw Collingbourne
Explore CourseBecause strings aren’t a numerical value, there’s no way to “perform string arithmetic.” But you can still perform arithmetic on a string, in a way, because they are an array. Let’s take a look at the basics of how to use strings in C.
What is a string?
A string is a char variable array, but it’s often treated and formatted specifically as a string. “Hello” is a string. “John Doe” is a string. “Greetings” is a string.
But though it looks like a single, discrete entity to you or me, it’s actually created out of components. When we create a string that reads “Hello,” we are really creating an array that says the following:
String[0] = H
String[1] = e
String[2] = l
String[3] = l
String[4] = o
And the string also has to terminate, which means there’s also:
String[5] = “\0”
So, a string is a collection of characters in a specific order. And that makes sense because each character has to be stored separately.
Once you understand strings, you know that you can manipulate them. You could reverse “Hello” (“olleH”), you could insert things into “Hello,” or you could insert things before or after “Hello.” This is all possible because “Hello” is stored in an array.
Programmers who are more familiar with object-oriented languages will notice quite a few differences in C. In Java (and other object-oriented languages), strings are usually objects that have a set of methods. In Java, a string and a character array will be two different things. In C, a string and a character array are essentially the same thing.
How do you create a string in C?
Let’s take a deeper look at how to store a string as an int main char:
#include <stdio.h>
int main() {
char helloWorld[12] = {‘H’, ‘e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’,’\0’};
printf(“%s\n”,helloWorld);
return 0;
}
This produces the following display string:
Hello World
In the above example, there are some important things to note. When declaring the “char,” you need to declare the number of characters. While “HelloWorld” has ten characters, we also inserted a space, making it eleven characters. Finally, every defined string has to finish with “\0,” which is the termination sequence. So really, it has a size of 12.
Later, we print the string. We use “%s” to show the printf() function that we are going to be sending a string along, and we use the “\n” to produce a printf enter command — a new line. We don’t need to print a new line in this situation because all we are printing is “Hello World.” But if we didn’t, the next block of text would be on the same line as the old block of text.
This is a precise way to create a string. But you also don’t need to go through all that rigmarole. You could likewise write:
char helloWorld[100] = “Hello World”;
C will automatically terminate the line. And it doesn’t hurt you to have additional slots in your char array. The issue is purely a memory and efficiency one. In the old days, it was more of a concern — you would want to have a char that was exactly the length that you needed it to be. Today, you need to concern yourself less with this.
When sizing string length, you should still make sure that you don’t recklessly over-allocate space. In the above example, “20” would certainly be more reasonable than a size of “100.” Database programmers may have a tendency to set a char to something like 255, but this is excessive for most applications.
How do you include string functions?
In addition to stdio.h, you will need to include string.h if you’re going to be operating with string functions. Your header would look like:
#include <stdio.h>
#include <string.h>
You don’t always need to use string functions in a program, which is why you don’t always include the string header by default. You can still declare a string without a string header, but you’re going to need string.h to perform dedicated string functions such as strlen() and strcat().
If you don’t include string.h, you will get an error when you start to call functions that are string-related. You should determine which libraries you will need early on in developing a program so you don’t include any that you don’t need.
How do you access a string?
Of course, storing a string isn’t helpful unless you can access it later. The most common method of accessing a string is printing it. You can print to the console with printf() or to a file with fprintf(). They both use the same methodology, so we’ll use printf().
You can print a string using the following code:
printf(“%s”,string);
In this situation, the “%s” serves as a format modifier that tells the printf() function to look for a string. A string is nothing but a list of characters, so you can also select each character individually.
This method would print a single character of a string:
printf(“%c”,string[2]);
In this case, it would print the 3rd character in the string (as an array starts with 0). The “%s” serves as a format modifier that tells the printf() function it is looking for a character.
When you tell printf() that it expects an %s (string), it goes through the entire array of characters. It’s important to conceptualize a string as an array of characters; a linear list of elements. The string name itself operates as a pointer to the first memory space of the string array.
You could print an entire string like this:
char string[12] = “Hello world”;
int i;
for(i = 0; i < strlen(string); i++) {
printf(“%c”,string[i]);
}
This will print:
Hello world
This is functionally no different than just printing the string. But if for some reason you wanted to print the string backward, you could instead:
for(i = strlen(string); i >= 0; i=i-1) {
printf(“%c”,string[i]);
}
This will print:
dlrow olleH
For the anatomy of a for() loop, you would want to review our article about for loop in C.
The ability to jumble up or otherwise access individual characters in the string is part of what makes having a string as an array useful. But it can also be a chore to manage, compared to more modern languages, which usually manage strings on a more automated basis.
How do you collect a string?
In addition to printing a string, you may need to collect input from a user. This is common when collecting a user’s login information, email address, password, or more.
You can use the scanf() function to collect strings. The scanf() function is a general function used to scan for user input, ranging from strings and characters to numbers such as ints and floating points.
An example:
char name[10];
printf(“Hey user, what’s your name? \n”);
scanf(“%s”,name);
printf(“Your name is: %s”, name);
The above code defines a string called “name.” It then asks the user what their name is and waits for a response, which will be a string. The string is stored in “name” and then printed out after the response is collected.
Once the scanf() function has been called and answered, the name string will always include the name information. This data can be further manipulated. You can figure out the length of the name, copy the name to another location, or even combine a first name with a last name (using concatenation).
Strlen(): How can you tell the length of a string?
Understandably, it’s sometimes important to know the length of a string. For instance, if you were going to iterate through a string as an array, you would need to know when to stop. You can find the length of a string using the strlen() function as so:
strlen(string);
This will return the length of the string, including its termination. An example of its use:
char helloWorld[12] = “Hello World”;
printf(“The string is: %zu ”,strlen(helloWorld));
The output will be:
12
In the above example, we used the format modifier “%zu.” %zu prints variables of size_t length.
You can also use strlen() for data validation. For example, you might want to use scanf() to collect user information from someone, but you might want to make sure that the user information is between 4 characters and 15 characters. It’s important to always validate your data; otherwise, it could cause system instability or even security issues.
Strcopy(): How do you copy a string?
You shouldn’t copy a string by simply making one string equal to another. This will not work because strings are a terminated array. Instead, you use a specific function — strcopy() — to copy a string to each other. Consider two strings, s1 and s2. You would copy s2 to s1 like so:
strcopy(s1,s2);
Here is an example:
char stringOne[10] = “Blue”;
char stringTwo[10] = “Green”;
printf(“%s”,stringOne);
printf(“/n”);
strcopy(stringOne,stringTwo);
printf(“%s”,stringOne);
The results:
Blue
Green
Between the printf() calls, stringTwo is copied to stringOne.
It’s very important to note that strcopy replaces the initial string. If you had wanted to retain stringOne and simply copy stringTwo to something else, you would have created a stringThree. If you had wanted to retain the data in stringOne but still replace stringOne, you would have had to copy stringOne to stringThree before copying stringTwo over.
So, the strcopy() function isn’t just a “copy” function — it’s a copy and replace function.
Strcat(): How do you concatenate a string?
Concatenation is the general term for adding one thing to the end of another. When you concatenate a string, you have the original string (s1) and the second string (s2). You would perform string concatenation like so:
strcat(s1,s2);
An example:
char s1[7] = “Hello ”;
char s2[6] = “World”;
strcat(s1,s2);
printf(“%s”,s1);
The result would be:
Hello World
Concatenation is frequently used for formatting. But you can also use it to create a single string out of multiple strings, such as creating a fullName string from a firstName and lastName. When you concatenate, you lose the first string — much like copying. This is something you might want to consider.
If you wanted to save your initial string, you might do something like this:
char firstName[10] = “John”;
char lastName[10] = “Doe”;
char fullName[20];
strcopy (fullName,firstName);
strcat(fullName,” “);
strcat(fullName,lastName);
printf(“%s”,fullName);
The result:
John Doe
In the first few lines, we declare three variables: firstName, lastName, and fullName. In the next, we use strcopy() to set the fullName to equal the firstName (John). In the next line, we add a space to the end of John. In the line after that, we concatenate the last name to the full name, leading to “John Doe.” And finally, we print it.
In the above example, we still have “John” stored in “firstName,” which wouldn’t be possible if we had simply used strcat on firstName and lastName.
Strcmp(): How do you compare a string?
How can you tell whether strings are identical? You use the strcmp() function. Here’s an example:
strcmp(s1,s2);
An example:
char stringOne[10] = “Green”;
char stringTwo[10] = “Blue”;
char stringThree[10] = “Blue”;
if(strcmp(stringOne,stringTwo)==0) {
printf(“String one and two are the same.\n”);
}
if(strcmp(stringTwo,stringThree)==0) {
printf(“String two and three are the same.\n”);
}
In this example, the program will print:
String two and three are the same.
The strcmp() function returns 0 if the strings are equal. It will return < 0 if the first character that doesn’t match is lower in string one than string two and > 0 if the first character that doesn’t match is lower in string two than string one.
This is an interesting case because it isn’t a binary comparison. It isn’t only asking if the strings are identical (though this is what it is most frequently used for), but it’s also asking how the strings compare to each other.
In particular, strcmp() can be used for functions that sort things alphabetically, because it can compare strings and determine whether they need to be moved up or down in a list depending on how they compare to others.
Sprintf(): Using sprintf() to write strings in C
In addition to using printf() for strings, you can also use sprintf(). Sprintf() is a function specifically designed for strings. The difference between sprintf() and printf() is that instead of printing to the console, it actually prints information into a string.
char string[50];
sprintf(string, “Hello world!”);
printf(%s,string);
In the above example, you declare a string character of length 50. You then use sprintf() to write “Hello world!” into the string itself. And from there, you print the string.
It can be easier to “print” to a string (rather than assign values to a string) if the string is complex, such as taking arguments like calculations.
Other important string functions: strchr() and strstr()
Strchr() returns a pointer to the first instance of a character in a string. It’s used like this:
strchr(s1, ch);
This will produce the appropriate char str.
Similarly, strstr() returns a pointer to the first instance of a string in a string. It’s used like so:
strstr(s1,s2);
Using strings in C
The above is a basic primer on using strings in C, but it’s by no means an exhaustive list. Much of what a developer will do in C involves strings. Critical to using strings is an in-depth understanding that strings are a type of array, though they are not just an array.
Whether displaying data to a user or collecting data from a user, strings will often be the most used format.
Developers should always remember to:
- Include string.h if they are going to be working with string-related functions.
- Make sure that they terminate strings if they are entering strings character by character.
- Allocate the correct char sizes for the appropriate string length.
Recommended Articles
Top courses in C (programming language)
C (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.