๐Ÿงต Strings in C Language

๐Ÿ”น What is a String in C?

A string in C is a sequence of characters stored in contiguous memory locations and terminated by a null character (\0).

๐Ÿ‘‰ In C, strings are essentially arrays of characters.

Article Algo

โœ… Why Use Strings?

  • Store text data like names, addresses, messages
  • Perform operations like comparison and concatenation
  • Essential for input/output operations

๐Ÿ“Œ String Declaration and Initialization

1๏ธโƒฃ Using Character Array

char name[20];
char name[20] = "Rahul";

2๏ธโƒฃ Using Pointer

char *name = "Rahul";

โš ๏ธ Important Notes

  • Strings must end with \0
  • String literals are read-only
  • Array-based strings can be modified

๐Ÿ“Œ String Input and Output

#include <stdio.h>

int main() {
  char name[20];
  printf("Enter your name: ");
  scanf("%s", name);
  printf("Hello %s", name);
  return 0;
}

๐Ÿ‘‰ For input with spaces, use: fgets(name, 20, stdin);

๐Ÿ“‚ Types of Strings in C

1๏ธโƒฃ Single-Dimensional String

char str[20] = "Hello";
#include <stdio.h>

int main() {
  char str[10] = "C Language";
  printf("%s", str);
  return 0;
}

2๏ธโƒฃ String Using Pointer

char *str = "Hello World";

Pointer strings are stored in read-only memory. Modifying them causes undefined behavior.

3๏ธโƒฃ Array of Strings (2D Character Array)

#include <stdio.h>

int main() {
  char names[3][10] = {"Amit", "Neha", "Ravi"};

  for(int i = 0; i < 3; i++) {
    printf("%s\n", names[i]);
  }
  return 0;
}

names[3][10] โ†’ 3 strings, each with 9 characters + null terminator

4๏ธโƒฃ Pointer Array of Strings

#include <stdio.h>

int main() {
  char *names[] = {"Amit", "Neha", "Ravi"};

  for(int i = 0; i < 3; i++) {
    printf("%s\n", names[i]);
  }
  return 0;
}

โœ” More memory-efficient than 2D arrays

๐Ÿ“š Common String Functions (<string.h>)

Function Description
strlen(str) Returns length of string
strcpy(dest, src) Copies src to dest
strcat(dest, src) Concatenates strings
strcmp(str1, str2) Compares two strings
strchr(str, ch) Finds character
strstr(str, sub) Finds substring

๐Ÿ“˜ Example: strlen() and strcpy()

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

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

  printf("Length: %lu\n", strlen(str1));
  strcpy(str2, str1);
  printf("Copied: %s", str2);
  return 0;
}

๐Ÿ“š FAQs on Strings in C

Q1. What is a string in C?

A sequence of characters terminated by \0.

Q2. How to declare a string?

Using char array or pointer.

Q3. Can we modify string literals?

No, it causes undefined behavior.

Q4. Difference between 2D array and pointer array?

2D arrays store actual data, pointer arrays store addresses.

Q5. How is string length calculated?

Using strlen(), excluding \0.

๐Ÿ”‘ Key Points to Remember

  • Strings are character arrays
  • Always end with \0
  • Use fgets for multi-word input
  • Use <string.h> functions