Strings in C programming language

 Here’s a clean, beginner-friendly blog you can use on Strings in C:


๐Ÿงต Strings in C: A Complete Beginner’s Guide

Strings are one of the most important concepts in C programming. Whether you're working with user input, text processing, or file handling, understanding strings is essential.


๐Ÿ”ค What is a String in C?

In C, a string is an array of characters terminated by a special character called the null character ('\0').

Example:

char name[] = "Hello";

This is stored in memory as:

H e l l o \0

๐Ÿ“ฆ Declaring and Initializing Strings

1. Using Character Array

char str[10] = "Hello";

2. Without Size (Auto-sized)

char str[] = "World";

3. Character by Character

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

๐Ÿ“ฅ Taking String Input

Using scanf()

scanf("%s", str);

⚠️ Stops reading at whitespace.

Using gets() (Not Recommended ❌)

gets(str);

Unsafe because it can cause buffer overflow.

Using fgets() (Recommended ✅)

fgets(str, sizeof(str), stdin);

๐Ÿ“ค Printing Strings

printf("%s", str);

๐Ÿงฐ Common String Functions

C provides built-in string functions in the header file:

#include <string.h>

1. strlen()

Finds length of string

strlen(str);

2. strcpy()

Copies one string to another

strcpy(dest, src);

3. strcat()

Concatenates (joins) two strings

strcat(str1, str2);

4. strcmp()

Compares two strings

strcmp(str1, str2);

๐Ÿ” Looping Through a String

for(int i = 0; str[i] != '\0'; i++) {
    printf("%c", str[i]);
}

⚠️ Common Mistakes

  • ❌ Forgetting the null character '\0'

  • ❌ Using gets() (unsafe)

  • ❌ Not allocating enough memory

  • ❌ Modifying string literals (undefined behavior)


๐ŸŽฏ Tips & Best Practices

  • Always use fgets() instead of gets()

  • Check string length before operations

  • Use sizeof() to avoid overflow

  • Prefer standard library functions

Comments

Popular posts from this blog

Kalonji nutritional profile and health benefits

Calcium hydroxide

Red Ginseng