Skip to content
Home » Embedded Systems » Embedded C » Strings in C

Strings in C

Tutorial illustration showing a rope knot and confused man with question mark, introducing C programming string concepts
Embedded Systems Learning Path
Part 16 of 129View Full Path →

KEY TAKEAWAYS

  • Strings in C are arrays of characters terminated by a null character ()
  • Standard library functions like strlen(), strcmp(), and strcpy() operate on null-terminated strings
  • Always allocate one extra byte for the null terminator when sizing string buffers
  • Use strncpy() and snprintf() instead of their unbounded counterparts to prevent buffer overflows

In C programming, Strings are defined as an array of characters or a sequence of characters terminated with a null character ‘‘.  When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character at the end by default.NE_stringFor example –

char c[]="Nerdy E";

Below is the Memory diagram for the above string –

string arrangement

Declaration of Strings in C

There are two ways to declare a string in c language.

  1. By char array
  2. By string literal

By Char Array

Lets take an example –

            char ch[10]={‘N’‘e’‘r’‘d’‘y’‘ ‘‘E’};

Strings - array_memory_layout

While declaring string, size is not mandatory. So we can write the above code as given below:

char ch[]={‘N’‘e’‘r’‘d’‘y’‘ ‘‘E’};

By string literal

Lets see an example of declaring by string literal –

char ch[]=”Nerdy E”;

strings_memory_layout

In such case, ” will be appended at the end of the string by the compiler.

The main difference between Char literal and String literal is that the string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.

Lets see this in a program

// C program to illustrate strings

#include<stdio.h>

int main()
{
    // declare and initialize string
    char str[] = "Nerdy E";
    char c[] = {'N','e','r','d','y',' ','E'};
    
    // print string
    printf("String Array Value is: %s \n",str);
    printf("Char Array Value is: %s \n",c);
    
    return 0;
}

What do you think the output would be?

str is a string literal — the compiler automatically appends a null terminator \0. c is a plain char array with no \0, making it unsafe to print with %s.

The output may appear identical in some environments because of how the compiler lays out stack memory — but this is undefined behavior. Never rely on it.

To safely print a char array with %s, explicitly add the null terminator:

Output

String Array Value is: Nerdy E
Char Array Value is: Nerdy ENerdy E   ← or garbage, or crash

If we make a small change, adding a null character

char c[] = {'N','e','r','d','y',' ','E', '\0'};

String Array Value is: Nerdy E
Char Array Value is: Nerdy E

Read Strings from the user

scanf()

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards until it encounters whitespace (space, newline, tab, etc.).

Lets take an example to see this –

// C program to read strings

#include<stdio.h>

int main()
{
    // declaring string
    char str[50];
    // taking input from user
    printf("Enter a string :");
    
    // reading string
    scanf("%s",str);
    
    // print string
    printf("The string is %s\n",str);

    return 0;
}

Output:

Enter a string :N_Electronics
The string is N_Electronics

Passing Strings to function

In the following example we have a string array variable which is passed to a function.

#include <stdio.h>

void displayString(char []);

int main(void) {
  // variables
  char message[] = "Hello Nerds";
    
  // print the string message
  displayString(message);
  
  return 0;
}

void displayString(char str[]) {
  printf("String: %s\n", str);
}

Here,

  • void is the returns type of the function i.e. it will return nothing.
  • displayString is the name of the function.
  • message[] is the character array (string).

Output

String: Hello World

Functions in Strings

String functions are used in computer programming languages to manipulate a string or query information about a string (some do both). There are many important string functions defined in “string.h” library. Some of them are given below :

Strlen

It returns the length of the string without including end character (terminating char ‘’).

Syntax : 

strlen(str1); //returns the length of str1

Strcpy

It copies the string str2 into string str1, including the end character (terminator char ‘’).

Syntax : 

strcpy(str1, str2);

Strcat

It concatenates two strings and returns the concatenated string.

Syntax : 

strcat(str1, str2); //Concatenates string str2 onto the end of string str1.

Lets use all these functions in a program to understand better.

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

int main () {

   char str1[12] = "Nerdy";
   char str2[12] = "Electronics";
   char str3[20];
   int  len ;

   /* copy str1 into str3 */
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );

   /* concatenates str1 and str2 */
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );

   /* total lenghth of str1 after concatenation */
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );

   return 0;
}

When the above code is compiled and executed, it produces the following result −

strcpy( str3, str1) :  Nerdy
strcat( str1, str2):   NerdyElectronics
strlen(str1) :  16

Explanation:

1. strcpy(str3,str1) gives Nerdy, since str3 is null.

2. strcat(str1,str2) then concatenates both the strings and gives combined result.

3. Finally, strlen(str1) gives the length of str1 ( which consists of the concatenated string )

Strcmp

It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison.

Syntax:

strcmp(str1, str2);

Returns 0 if str1 and str2 are the same;

less than 0 if str1<str2;

greater than 0 if str1>str2.

Lets take an example –

#include <stdio.h>
#include <string.h>
int main()
{
     char s1[25] = "NerdyElectronics";
     char s2[25] = "NerdyElectronics.com";
     if (strcmp(s1, s2) ==0)
     {
        printf("string 1 and string 2 are equal");
     }else
      {
         printf("string 1 and 2 are different");
      }
     return 0;
}

Output

Can you guess what the output will be?

string 1 and 2 are different

Strrev

The strrev(string) function returns reverse of the given string.

Syntax

strrev(str);

Strlwr

The strlwr(string) function returns string characters in lowercase.

Syntax

strlwr(str);

Strupr

The strupr(string) function returns string characters in uppercase.

Now let’s see a simple example using these 3 functions.

#include<stdio.h>  
#include <string.h>    
int main(){    
   char str[20]; 
   char str1[20];
   char str2[20];   
   printf("Enter string: ");    
   gets(str);     //reads string from console    
   printf("String is: %s",str);    
   printf("\nReverse String is: %s",strrev(str));  
   str1 = strlwr(str);   //converts string into lowercase
   printf("\nLowercase String is: %s",str1);
   str2 = strupr(str1);  //converts string into uppercase
   printf("\nUppercase String is: %s",str2);
   return 0;    
}

Output

Enter string: NERDY
String is: NERDY
Reverse String is: YDREN
Lowercase String is: nerdy
Uppercase String is: NERDY

Try to use all these functions while using Strings, it will help you understand better.

 

📖 Related: Most common pitfalls in C Programming Language and how to avoid them

2 thoughts on “Strings in C”

  1. In this example
    #include
    int main()
    {
    // declare and initialize string
    char str[] = “Nerdy E”;
    char c[] = “‘N’,’e’,’r’,’d’,’y’,’ ‘,’E'”;

    // print string
    printf(“String Array Value is: %sn”,str);
    printf(“Char Array Value is: %sn”,c);

    return 0;
    }
    In this example the output is not correct.

Leave a Reply

Your email address will not be published. Required fields are marked *