Strings in C Language: Complete Guide with Examples, Programs & String Functions

 

Understanding Strings and String Library Functions in C Language

🔹 What are Strings in C?

In C, a string is a collection of characters stored in a character array, ending with a null character ('\0'). Strings help us store and manipulate text data like names, sentences, passwords, etc.

✅ Example 1: Basic String Declaration

#include <stdio.h>

int main() {
    char name[20] = "Jatasya";
    printf("Name: %s\n", name);
    return 0;
}
🟢 Output:
Name: Jatasya

🔹 String Input and Output

✅ Example 2: Using scanf() and gets()

#include <stdio.h>

int main() {
    char name1[20], name2[20];

    printf("Enter name using scanf: ");
    scanf("%s", name1);  // Only reads first word

    getchar(); // To consume leftover newline

    printf("Enter full name using gets: ");
    gets(name2);  // Reads full line (unsafe)

    printf("Using scanf: %s\n", name1);
    printf("Using gets: %s\n", name2);

    return 0;
}
🟢 Sample Output:
Enter name using scanf: Vivan
Enter full name using gets: Vivan Bambhaniya
Using scanf: Vivan
Using gets: Vivan Bambhaniya
⚠️ gets() is dangerous and outdated. Use fgets() instead.

✅ Example 3: Using fgets() Safely

#include <stdio.h>

int main() {
    char name[50];
    
    printf("Enter your full name: ");
    fgets(name, sizeof(name), stdin);  // Safer input

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

🔧 String Library Functions

Master these essential string manipulation functions

✅ Example 4: strlen() - String Length

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

int main() {
    char city[] = "Delhi";
    int len = strlen(city);

    printf("Length of %s is %d\n", city, len);
    return 0;
}
🟢 Output:
Length of Delhi is 5

✅ Example 5: strcpy() - Copy String

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

int main() {
    char source[] = "OpenAI";
    char destination[20];

    strcpy(destination, source);

    printf("Copied String: %s\n", destination);
    return 0;
}
🟢 Output:
Copied String: OpenAI

✅ Example 6: strcat() - Concatenate Strings

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

int main() {
    char greet[50] = "Hello ";
    char name[] = "World";

    strcat(greet, name);

    printf("Greeting: %s\n", greet);
    return 0;
}
🟢 Output:
Greeting: Hello World

✅ Example 7: strcmp() - Compare Strings

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

int main() {
    char pass1[] = "admin";
    char pass2[] = "admin";

    if (strcmp(pass1, pass2) == 0)
        printf("Passwords match!\n");
    else
        printf("Passwords do not match.\n");

    return 0;
}
🟢 Output:
Passwords match!

✅ Example 8: strchr() - Find Character

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

int main() {
    char text[] = "Programming";
    char *ptr = strchr(text, 'g');

    if (ptr)
        printf("Character found at position: %ld\n", ptr - text);
    else
        printf("Character not found.");

    return 0;
}
🟢 Output:
Character found at position: 3

✅ Example 9: strstr() - Find Substring

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

int main() {
    char str[] = "I love programming in C";
    char *sub = strstr(str, "programming");

    if (sub)
        printf("Found substring: %s\n", sub);
    else
        printf("Substring not found.");

    return 0;
}
🟢 Output:
Found substring: programming in C

🚀 Advanced String Programs

Build your own string functions and solve real problems

✅ Example 10: Create Your Own strlen()

#include <stdio.h>

int my_strlen(char str[]) {
    int count = 0;
    while (str[count] != '\0')
        count++;
    return count;
}

int main() {
    char s[] = "CustomLength";
    printf("Length: %d\n", my_strlen(s));
    return 0;
}
🟢 Output:
Length: 12

✅ Example 11: Palindrome Checker

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

int is_palindrome(char str[]) {
    int i = 0, j = strlen(str) - 1;
    while (i < j) {
        if (str[i] != str[j])
            return 0;
        i++; j--;
    }
    return 1;
}

int main() {
    char word[50];
    printf("Enter a word: ");
    scanf("%s", word);

    if (is_palindrome(word))
        printf("%s is a palindrome.\n", word);
    else
        printf("%s is not a palindrome.\n", word);

    return 0;
}
🟢 Sample Output:
Enter a word: madam
madam is a palindrome.

✅ Example 12: Word Counter from Sentence

#include <stdio.h>

int main() {
    char str[100];
    int i, words = 0;

    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);

    for (i = 0; str[i] != '\0'; i++) {
        if ((str[i] == ' ' || str[i] == '\n') && 
            str[i+1] != ' ' && str[i+1] != '\n' && str[i+1] != '\0') {
            words++;
        }
    }

    printf("Total words: %d\n", words + 1);
    return 0;
}
🟢 Sample Output:
Enter a sentence: I love programming
Total words: 3

✅ Conclusion

Strings in C may look tricky, but they become easy once you understand the basics. By mastering string functions like strlen, strcpy, strcmp, and learning how to manipulate character arrays, you can build powerful text-based features in your programs.

Try building mini tools like a password matcher, word counter, or even a simple chat bot using what you learned today!

❓ Frequently Asked Questions

1. What's the difference between char[] and char* in C?

  • char[] allocates memory at compile-time.
  • char* points to a memory location; you must allocate or assign it.

2. Can I use strcpy() with char*?

Yes, as long as the destination pointer points to enough allocated memory.

3. Is gets() safe to use?

No, it's dangerous and removed from modern C standards. Use fgets() instead.

4. Do I need to include any header for string functions?

Yes, always include #include <string.h> for using string library functions.

5. How do I reverse a string safely?

Write your own reverse function using a loop or use a trusted implementation, since strrev() is not standard.


Post a Comment

0 Comments