Loading...

Strings in C

In C, a string is a sequence of characters stored in a character array and terminated with a null character '\0'. Unlike other languages, C does not have a built-in string type.

Declaring and Initializing Strings

Declaration:

Strings are declared as character arrays:

char str[20]; // Declares a string with space for 20 characters

Initialization:

Strings can be initialized in multiple ways:

char str1[] = "Hello";  // Automatically adds '\0'
char str2[6] = "Hello"; // Explicitly specifying size
char str3[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Character array

Input and Output of Strings

Using scanf and printf

scanf can be used for input, but it does not handle spaces. gets and fgets are used for multi-word input.

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    scanf("%s", name);  // Reads a single word

    printf("Hello, %s\n", name);
    return 0;
}

Using gets and fgets

To read a full sentence:

#include <stdio.h>

int main() {
    char sentence[100];

    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin);  // Reads a full line

    printf("You entered: %s", sentence);
    return 0;
}

String Functions in C

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

Common String Functions

  • strlen(str) - Returns the length of a string
  • strcpy(dest, src) - Copies one string into another
  • strcat(dest, src) - Concatenates two strings
  • strcmp(str1, str2) - Compares two strings

Example: String Functions

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

int main() {
    char str1[20] = "Hello";
    char str2[20] = "World";
    char str3[40];

    // String length
    printf("Length of str1: %ld\n", strlen(str1));

    // String copy
    strcpy(str3, str1);
    printf("Copied string: %s\n", str3);

    // String concatenation
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);

    // String comparison
    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal.\n");
    } else {
        printf("Strings are not equal.\n");
    }

    return 0;
}

String and Pointers

Strings can also be handled using pointers:

#include <stdio.h>

int main() {
    char *str = "Hello, World!";
    printf("%s\n", str);
    return 0;
}

Strings are an essential part of C programming, used for handling text data efficiently. Understanding string functions and manipulation techniques is crucial for effective programming.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!