Strings
String handling in C
Introduction
In this lesson, you'll learn about strings in C. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with string handling in c.
C has its own approach to string handling in c, which we'll explore step by step.
The C Way
Let's see how C handles this concept. Here's a typical example:
#include <string.h>
// C - strings are char arrays
char s[] = "Hello";
int len = strlen(s);
// No built-in toUpperCase - write your own
char concat[50];
strcpy(concat, s);
strcat(concat, " World");
int eq = strcmp(s, "Hello") == 0;
// Strings are mutable char arrays
s[0] = 'J'; // "Jello"Comparing to Java
Here's how you might have written similar code in Java:
// Java - String is a class
String s = "Hello";
int len = s.length();
String upper = s.toUpperCase();
String concat = s + " World";
boolean eq = s.equals("Hello");
// Strings are immutable
s = s + "!"; // creates new StringYou may be used to different syntax or behavior.
C strings are null-terminated char arrays
You may be used to different syntax or behavior.
No String class - use char[] and string.h functions
You may be used to different syntax or behavior.
strcmp() returns 0 for equal, not true
You may be used to different syntax or behavior.
Must manage buffer sizes manually
Step-by-Step Breakdown
1. String Basics
C strings are arrays of chars ending with '\0' (null terminator).
char s1[] = "Hello"; // compiler adds \0
char s2[6] = {'H','e','l','l','o','\0'};
// s1 is actually: ['H','e','l','l','o','\0']
printf("%zu", sizeof(s1)); // 6 (5 chars + null)2. String Functions
The string.h header provides string manipulation functions.
#include <string.h>
char a[50] = "Hello";
char b[] = "World";
strlen(a); // 5 (doesn't count \0)
strcpy(a, b); // a = "World"
strcat(a, "!"); // a = "World!"
strcmp(a, b); // 0 if equal
strncpy(a, b, 3); // copy at most 3 chars3. Buffer Safety
Always ensure your buffers are large enough for the string plus null terminator.
String s = a + b; // Java handles size// C - you manage the buffer!
char result[100]; // must be big enough
if (strlen(a) + strlen(b) < sizeof(result)) {
strcpy(result, a);
strcat(result, b);
}Common Mistakes
When coming from Java, developers often make these mistakes:
- C strings are null-terminated char arrays
- No String class - use char[] and string.h functions
- strcmp() returns 0 for equal, not true
Key Takeaways
- Strings are null-terminated char arrays
- Use string.h for strlen, strcpy, strcat, strcmp
- Always ensure buffers are large enough
- Use strn* functions to limit operations