String

C Programming Tutorial: Strings

Strings in C Programming

Welcome to the Codes With Pankaj "Strings in C Programming" tutorial! This tutorial will guide you through the concepts and practical applications of strings in C.

Table of Contents


1. Introduction to Strings

In C, a string is an array of characters terminated by a null character ('\0'). Strings are used to store and manipulate text.

2. Declaring and Initializing Strings

Declaring a String

To declare a string, use a character array.

char string_name[size];

Example:

char str[50];

Initializing a String

Strings can be initialized at the time of declaration.

char string_name[] = "string_literal";

Example:

char str[] = "Hello, World!";

The null character ('\0') is automatically added at the end of the string.

3. String Input and Output

Using scanf and printf

#include <stdio.h>

int main() {
    char str[50];
    printf("Enter a string: ");
    scanf("%s", str);  // Note: %s reads input until a space is encountered
    printf("You entered: %s\n", str);
    return 0;
}

Using gets and puts

#include <stdio.h>

int main() {
    char str[50];
    printf("Enter a string: ");
    gets(str);  // Note: gets is unsafe and should be avoided
    printf("You entered: ");
    puts(str);
    return 0;
}

Using fgets

#include <stdio.h>

int main() {
    char str[50];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Safe alternative to gets
    printf("You entered: ");
    puts(str);
    return 0;
}

4. String Functions in C

The <string.h> library provides various functions to manipulate strings.

strlen: Get the Length of a String

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

int main() {
    char str[] = "p4n";
    printf("Length of string: %zu\n", strlen(str));
    return 0;
}

strcpy: Copy a String

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

int main() {
    char src[] = "p4n";
    char dest[50];
    strcpy(dest, src);
    printf("Copied string: %s\n", dest);
    return 0;
}

strcat: Concatenate Strings

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

int main() {
    char str1[50] = "p4n";
    char str2[] = " tutorial";
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    return 0;
}

strcmp: Compare Strings

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

int main() {
    char str1[] = "cwp";
    char str2[] = "p4n";
    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("Strings are equal\n");
    } else if (result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is less than str2\n");
    }

    return 0;
}

5. Manipulating Strings

Finding a Character in a String

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

int main() {
    char str[] = "Codes With Pankaj";
    char *pos = strchr(str, 'W');
    if (pos != NULL) {
        printf("Character found at position: %ld\n", pos - str);
    } else {
        printf("Character not found\n");
    }
    return 0;
}

Finding a Substring in a String

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

int main() {
    char str[] = "Codes With Pankaj";
    char *pos = strstr(str, "Pankaj");
    if (pos != NULL) {
        printf("Substring found at position: %ld\n", pos - str);
    } else {
        printf("Substring not found\n");
    }
    return 0;
}

6. Pointers and Strings

Strings can be manipulated using pointers, providing efficient ways to handle them.

Example: Printing a String Using Pointers

#include <stdio.h>

int main() {
    char str[] = "Codes With Pankaj";
    char *ptr = str;

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

    return 0;
}

7. Common Mistakes and Best Practices

Common Mistakes

  1. Buffer Overflow: Ensure the destination array is large enough when using functions like strcpy and strcat.

    char src[] = "This is a very long string";
    char dest[10];
    strcpy(dest, src); // Error: dest is too small
  2. Uninitialized Strings: Always initialize strings before use.

    char str[10];
    printf("%s", str); // Error: str is uninitialized
  3. Unsafe Input Functions: Avoid using gets due to its vulnerability to buffer overflows. Use fgets instead.

Best Practices

  1. Use Safe Functions: Use fgets for input and ensure buffer sizes are respected.

  2. Null-Termination: Always ensure strings are properly null-terminated.

  3. Check Return Values: Always check the return values of functions like strcpy, strcat, and fgets.

8. Exercises

Try these exercises to practice using strings in C:

  1. Exercise 1: Write a program to find the length of a string without using strlen.

  2. Exercise 2: Write a program to concatenate two strings without using strcat.

  3. Exercise 3: Write a program to copy one string to another without using strcpy.

  4. Exercise 4: Write a program to count the number of vowels in a string.

  5. Exercise 5: Write a program to reverse a string.


We hope this tutorial has helped you understand strings in C programming. Practice with the exercises provided to reinforce your understanding. Happy coding!

For more tutorials, visit www.codeswithpankaj.com.

Last updated