Home

 › 

Articles

 › 

C Strings In Programming Explained, With Examples

C Strings in Programming

C Strings In Programming Explained, With Examples

Arrays are usually represented using integer values, but this isn’t always the case. When we’re talking about C strings, it’s a relatively simple concept. These are a type of array used in the C programming language, consisting of a sequence of characters rather than integer values.

As such, C strings are used to store and modify text data, rather than numeric data. Read on to find out more about C strings and how they’re used, with examples. One important concept to keep in mind when working with C strings is that they are mutable, meaning that the contents of a string can be modified.

This can be useful for implementing algorithms that require modifying string data, but it also requires careful attention to memory management to avoid buffer overflows and other common pitfalls.

What Are C Strings?

As mentioned before, a C string is used to represent text data in the C programming language. They can be thought of as a one-dimensional array. Unlike strings in C++, C strings have a fixed length. The string sequence is also always terminated by the special null character, “\0.”

The null character is critical to implementing a string since it’s the identifier for the string’s endpoint. For example, consider the following string:

char string[] = “Hello”;

Here, the data type is defined as the “character” type, the name of the string is designated “string” and the string is initialized with the character sequence “Hello.” We don’t need to explicitly include the null character, since the use of double quotes indicates to the compiler that the null character should be included.

It’s worth noting that a bonus of using strings is that they’re mutable. This means the contents can be modified as needed. To do this, you need to be cautious about memory allocation, but this is a great benefit for many programming situations.

Different Ways to Declare a C String

Generally, there are two methods for declaring a string in C. These are either by char array or by string literal. Let’s take a closer look at these.

Declaring a C string by char array

To declare a C string by char array, we don’t need to specify the string size initially. The size is automatically calculated by the compiler, based on string length plus the null character, of course. The previous code is actually an example of implementing a C string using a char array.

Declaring a C string by string literal

Next, let’s examine the alternative way to declare a string. Using the same example, we can implement the string as follows:

char *myString = “Hello”;

Here, we use the asterisk to designate that the “myString” variable is a pointer to the “char” keyword, and is initialized with the string literal “Hello.”

One of the main differences between declaring by string literals or char arrays is that string literal declarations cannot be modified as easily. Doing so can result in unpredictable behavior.

How Are C Strings Initialized?

There are a few different ways to initialize a C string. We’re going to cover them in this section.

How to initialize a C string of a specific size

The examples we’ve given previously show that we can initialize a string without assigning a size to it. However, we can assign a predefined size as follows:

char string[10] = “Hello”;

This initializes the string literal with size 10. It’s important to remember to always declare a string of size equal to at least n + 1, where n is the size of the string you want to store. This is to allow space for the null character.

How to initialize a C string character by character

You can also initialize a C string character by character, which can be useful if you need to modify the string contents individually, or include non-printable characters. Take the following example code:

char string[11] = 
{ 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '\0'};

Here, we’ve initialized the string with individual characters. Take note that we’ve designated the size as n+1, to make room for the null character at the end of the string.

Although we indicated the string size here, this isn’t necessary, as the compiler can calculate this from the characters. For example:

char string[] = { 'H', 'e', 'l' ,'l', 'o', 'W', 'o', 'r', 'l', 'd', '\0\};

The compiler will determine the string size, so we don’t need to specify it.

How Do You Traverse a C String?

A very useful way to work with strings is to traverse them, just as we often do with numeric data. This is especially helpful when working with an especially large string when you only need to access a certain part of it.

However, the process for this is slightly different from traversing a traditional array of integers. The main methods for traversing strings are described next.

Traversing a string using string length

First, you can traverse a string by using the length of the string. Consider the following code:

#include <stdio.h>
#include <string.h>

int main() {
    char myString[] = "Hello, world!";
    int length = strlen(myString);
    
    for (int i = 0; i < length; i++) {
        printf("%c ", myString[i]);
    }
    
    return 0;
}


First, we include the directives that allow input and output operations, as well as string functions. A C string called “myString” is declared, and initialized with the “Hello, world!” string literal. The strlen()function is then used to determine the string length, which is stored in the “length” variable.

Finally, we use a for loop to iterate over the string characters, using the variable “i.” Each character is then printed to the console, as seen in the below image.

c strings
Initializing a C string.

©History-Computer.com

Traversing a string using the null character

Another way to traverse a string is by using the null character. This is a similar process, except we use the null character to determine when the string is terminated. If we look at the following code:

#include <stdio.h>

int main() {
    char myString[] = "Hello, world!";
    
    for (int i = 0; myString[i] != '\0'; i++) {
        printf("%c ", myString[i]);
    }
    
    return 0;
}

As before, we declare “myString” and initialize it with “Hello, world!” We still use a for loop, but we iterate this until the null character is reached, rather than calculating the string length first. Take a look at the output in the screenshot below, to see that it’s the same as before.

c strings
Using the null character.

©History-Computer.com

How to Read a String

Just as we can traverse strings with multiple methods, there are a few ways to read a string. Usually, you’d use the “scanf” function or the “fgets()” function. Both of these are illustrated next.

Using the “scanf()” function

The “scanf” function reads the C string input and stores it in some variable specified. Take a look at this code:

#include <stdio.h>

int main() {
    char myString[100];
    
    printf("Enter a string: ");
    scanf("%s", myString);
    
    printf("You entered: %s", myString);
    
    return 0;
}

The “myString” string is declared with size 100. “Printf()” is then used to prompt user input in the console, and then “scanf()” is used to read the string.

We use “%s” to print the string that’s passed, and the string is stored in the “myString” array. The console will prompt user input, so if we enter “Hello, world!” as the input, we receive the output as shown below.

c strings
Using “%s” to print the string.

©History-Computer.com

Note that “scanf()” can only read up to the first whitespace character (i.e. a tab, newline or space). Therefore, only the “Hello” part of the string is printed. To read the entire string including spaces, we need to modify the function, e.g.:

#include <stdio.h>

int main() {
    char myString[100];
    
    printf("Enter a string: ");
    scanf("%[^\n]s", myString);
    
    printf("You entered: %s", myString);
    
    return 0;
}

Here, we’ve changed the function to include “[^\n], which tells the compiler to store space-separated strings when a whitespace character is encountered. The output we receive includes the whole string, as shown in the image.

Using the “fgets()” function

The “fgets()” function is useful when you need to read a complete string, including any whitespace characters. An example is shown next.

#include <stdio.h>
#include <string.h>

int main() {
    char myString[100];
    
    printf("Enter a string: ");
    fgets(myString, sizeof(myString), stdin);
    
    size_t len = strlen(myString);
    if (len > 0 && myString[len-1] == '\n') {
        myString[--len] = '\0';
    }
    
    printf("You entered: %s\n", myString);
    
    return 0;
}

We declare a similar string here, as well as a prompt for entering a string. The “fgets()” function is then used to read the string. However, typically, “fgets()” includes the newline character in the input string, which would give a blank line after the string in this case.

To remove this, we use “strlen()” and an if statement. The string length is determined by “strlen()”, the string length is checked, and then the newline character is replaced by a null character. We can see the output is identical to the “scanf()” example, given the same input string.

c strings
Determining and checking the string length.

©History-Computer.com

Passing a C String to a Function

Another way to work with C strings is to pass them to a function, similarly to how we would pass an array of integers. Take this example:

#include <stdio.h>

void myFunction(char *str) {
    printf("String: %s\n", str);
}

int main() {
    char myString[] = "Hello, world!";
    myFunction(myString);
    return 0;
}

In this case, the “myFunction()” function takes the “char *” pointer as an argument. The function is then called, and the “myString” string is passed to the function. The function uses the pointer to access the string, which is then printed as seen below.

c strings
Passing the “myString” string to the function.

©History-Computer.com

Pointers With Strings

We used a pointer as an argument in the previous example, but pointers can also be used to point to the string’s starting address, much like we can do with integer arrays. For example:

#include <stdio.h>

int main() {
  char myString[] = "Hello, world!";
  char *myPointer = myString;

  while (*myPointer != '\0') {
    printf("%c", *myPointer);
    myPointer++;
  }

  return 0;
}

As before, we declare the string “myString’, then a pointer called “myPointer” is created, which points to the initial character. Then, we use a while loop to print each string character until we reach the null character. The “++” operator is used to increment the pointer along the string. You can see the output below.

c strings
Creating “myPointer.”

©History-Computer.com

Wrapping Up

Strings are an essential tool in a C developer’s arsenal. They can be used with many different functions and can behave similarly to integer arrays in many scenarios. For example, individual elements can be accessed and modified, and the string can be traversed.

Every C string is terminated by the special null character, and are often used with pointers to modify individual string characters. When working with text data, understanding how to manipulate strings is vital.

Frequently Asked Questions

What is a C string?

A C string is a representation of text data used in the C programming language. They can be manipulated in many similar ways to integer-based arrays, and can be thought of as a one-dimensional array.

How do you terminate a C string?

All C strings must be terminated using the special null character, which designates the endpoint of the string. In many cases, the null character is automatically included, if double quotes are used around the string.

How are C strings declared?

C strings can be declared either by using a character array or a string literal. If using a string literal, the string cannot be modified.

How are C strings initialized?

C strings can be initialized without a specific size, with a specific size or character by character. If you are declaring the size, it’s necessary to specify a size equal to or greater than n+1, as space is required for the mandatory special null character.

How are C strings printed?

C strings can be printed using the “printf()” function, as well as the “%s” specifier. If you’re using the “scanf()” function, you can use the “%[^\n]” specifier to include any newline characters from the input.

How do you convert numbers into a string?

To convert numbers into a string, you can use the “sprintf()” function.

What are some of the most common functions used with C strings?

There are so many functions that can be used with C strings, but some of the most common include “strcpy()” (for copying the contents of a string to another string), “strlen()” (returns string length), “strcmp() (compares two strings), “strcat()” (concatenates/combines two strings), “strlwr()” (converts string to lowercase characters), “strupr()” (converts string characters to uppercase), “scanf()” and “fgets()” (both used for reading a string.)

To top