Strings in C with Examples

Get Certified in C Programming and Take Your Skills to the Next Level

Strings are one of the most fundamental data types in programming. Though C does not have a dedicated string data type, we can represent strings using character arrays. String manipulation forms an essential part of most C programs. The use of strings in C programming, including how to define, initialise, modify, input, and output strings, will be covered in this article.

Character Arrays vs. Strings in C

In C, strings are actually one-dimensional character arrays terminated with a null character ‘\0’. For example:

char myString[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Here, myString is a character array that can hold 6 characters. The last element \0 is the null terminating character that marks the end of the string.

On the other hand, a regular character array does not need to be null terminated:

char chars[5] = {'a', 'b', 'c', 'd', 'e'};

So, in summary, the main differences between a character array and a string in C are:

  • The null character, “0,” is appended internally by the compiler in the case of a character array, but we must add it ourselves to the end of the array in this case.
  • The characters of the array can be changed, unlike the string literal, which cannot be changed to another set of characters.

Declaring and Initializing C Strings

To declare a string in C, you specify the number of characters it can hold along with the char keyword:

char myString[100]; // can hold up to 99 chars + '\0'

To initialize a string, you can assign a string literal enclosed in double quotes:

char myString[6] = "Hello"; // ['H','e','l','l','o','\0']

Note the use of double quotes which indicates a string literal, and the ‘\0’ null character automatically appended.

declaring and initializing string in c

Ways to Initialize a String in C

There are several ways to initialize strings in C:

1) Assigning a String Literal Without Size

When we assign a string literal without specifying a size like:

char str[] = "Hello";

C automatically calculates the size of the string literal “Hello”, including the null terminator \0. So it allocates a char array of size 6 to store the string.

The advantage of this method is that we don’t have to manually specify any size. C takes care of memory allocation based on the literal.

The disadvantage is that we cannot resize the array later since the size is fixed at initialization.

2) Assigning a String Literal With Size

When we specify a size like:

char str[50] = "Hello";

Here, C will allocate a char array of size 50, initialize it with the literal “Hello”, and pad the remaining space with null terminators \0.

The advantage is that we can accommodate future string size increases up to the allocated memory.

The disadvantage is that excess memory may get allocated if we specify a very large size.

3) Character By Character Initialization With Size

When initializing character by character, we specify sizes like:

char str[6]; 
str[0] = 'H';
str[1] = 'e'; 
...
str[5] = '\0';

Here, we have full control over each character inserted into the array. But it involves more work manually inserting each character.

The size helps prevent accidental buffer overflows by limiting writes beyond the array size. But strings without null terminators can cause issues.

4) Character By Character Initialization Without Size

We can also initialize strings character by character without specifying size:

char str[] = {'H','e','l','l','o','\0'};

C automatically allocates the size to hold the initialized characters plus the null terminator.

This gives both flexibility of character by character initialization as well as safety of automatic memory allocation. But we lose the ability to resize arrays later.

String Examples

Let’s look at some common programming examples related to strings in C:

1. Printing Strings

We can print strings normally with printf:

char str[] = "Hello World";
printf("%s", str);

Output:
Hello World

To print strings, use the%s format specifier.

2. Reading String Input

To read a string from user input:

char str[50];
scanf("%s", str);
printf("%s", str);

Input:
DataFlair

Output:
DataFlair

3. Reading Strings with Spaces

scanf() stops at whitespace. To read strings with spaces:

char str[50];
fgets(str, 50, stdin);
puts(str);

Input:
DataFlair Tutorials

Output:
DataFlair Tutorials

We can also use scanf() with scanset:

char str[20];
scanf("%[^\n]s", str);
printf("%s", str);

4. Finding String Length

Get string length with a loop:

char str[] = "Hello";
int len = 0;
while(str[len] != '\0') {
  len++; 
}
printf("Length is: %d", len);

Output:
Length is: 5

Or use strlen() from string.h

5. Passing Strings to Functions

void printStr(char str[]) {
  printf("%s", str); 
}
int main() {
  char str[] = "DataFlair";
  printStr(str);
  return 0;
}

Output:
DataFlair

So, in summary, strings in C can be used in various ways as illustrated by these examples. The key is choosing the right functions based on your specific string processing needs.

String.h Functions

FunctionDescription
strlen(s)Calculates the length of string s
strcpy(s1, s2)Copies string s2 into string s1
strcat(s1, s2)Concatenates string s2 to end of string s1
strcmp(s1, s2)Compares string s1 and s2
strchr(s,ch)Finds first occurrence of char ch in string s
strstr(s1, s2)Finds first occurrence of string s2 in string s1
strlwr(s)Converts string s to lowercase
strupr(s)Converts string s to uppercase
memcpy(s1, s2, n)Copies n chars from string s2 to s1
memmove(s1, s2, n)Moves n chars from string s2 to s1
#include <stdio.h>
#include <string.h>

int main() {
  char s1[10] = "hello";
  char s2[10] = "world";
  
  // strlen()
  int len = strlen(s1);
  printf("Length of s1: %d\n", len);

  // strcpy()  
  strcpy(s2, s1);
  printf("s2 after strcpy: %s\n", s2);

  // strcat()
  strcat(s1, s2);
  printf("s1 after strcat: %s\n", s1);

  // strcmp()
  int result = strcmp(s1, s2);
  if(result == 0) {
    printf("s1 and s2 are equal\n");
  } else {
    printf("s1 and s2 are not equal\n");
  }

  // strlwr()
  strlwr(s1);
  printf("s1 after strlwr: %s\n", s1);

  // strupr()
  strupr(s1);
  printf("s1 after strupr: %s\n", s1);
  return 0;
}

Output:

Length of s1: 5
s2 after strcpy: hello
s1 after strcat: hellohello
s1 and s2 are not equal
s1 after strlwr: hellohello
s1 after strupr: HELLOHELLO

Input and Output of Strings

We can use scanf() and printf() for input and output of strings in C:

#include <stdio.h>

int main() {
  char name[50];

  // Input string  
  printf("Enter your name: ");
  scanf("%s", name); // %s format specifier 
  
  printf("Hello %s!", name);
  
  return 0;
}

Some points to note:

  • %s format specifier is used in scanf() and printf() to read and write strings.
  • scanf() stops reading input at the first space, so it won’t read full strings containing spaces.
  • To read strings with spaces, you can use fgets().

String Handling Best Practices

When handling strings in C, some best practices include:

  • Always allocate sufficient memory to hold the string contents and null terminator.
  • Use the length limiting modifiers like %49s in scanf() to avoid buffer overflow.
  • Use strlen() to get string length before operations like concatenation.
  • Use strcpy() and strcat() safely to avoid buffer overflows.
  • Free dynamically allocated strings using free() to avoid memory leaks.
  • Use const keyword for string literals to avoid accidentally modifying them.

Following these practices will help avoid common pitfalls like buffer overflows and memory leaks.

Some important points

  • The character array’s limits are not checked by the compiler. As a result, there may be instances where a string’s length exceeds the character array’s size, overwriting some crucial information.
  • We may utilise the built-in function gets(), which is defined in a header file string, instead of using scanf.h. Only one string can be passed to the gets() function at a time.

Strings and Pointers in C

In C, strings are closely linked to pointers. In fact, C treats string literals as constant character pointers. For example:

char *ptr = "Hello";

Here ptr contains the address of the first character ‘H’. We can access each character using pointer arithmetic:

ptr[0]; // 'H' 
ptr[1]; // 'e'

Many string manipulation functions also take pointers as arguments rather than arrays:

strlen(ptr); // ptr pointing to a string

So, pointers provide an efficient way to manipulate strings by directly accessing character data. Learning about pointers helps gain mastery over strings in C.

#include <stdio.h>

int main() {
    char phrase[] = "Welcome to DataFlair Tutorials";
    char *ptr = phrase; // Pointer to the beginning of the string

    printf("Original Phrase: %s\n", phrase);
    
    // Using a pointer to print the phrase character by character
    printf("Phrase (using pointer): ");
    while (*ptr != '\0') {
        printf("%c", *ptr);
        ptr++; // Move the pointer to the next character
    }
    printf("\n");

    // Reset the pointer to the beginning of the phrase
    ptr = phrase;

    // Find and print the length of the phrase using a pointer
    int length = 0;
    while (*ptr != '\0') {
        length++;
        ptr++;
    }
    printf("Phrase Length: %d\n", length);

    return 0;
}

Output:

Original Phrase: Welcome to DataFlair Tutorials
Phrase (using pointer): Welcome to DataFlair Tutorials
Phrase Length: 29

Conclusion

String manipulation forms a key part of C programming. In this article, we learned the basics of strings in C – declarations, initializations, input/output, manipulation functions and relationship with pointers. C strings provide a lot of flexibility but also require some care to use safely and efficiently. With this foundation, you can confidently handle strings in your C applications.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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