04/22/2025 1
STRINGS
LECTURE 7- CSE 1102
STRUCTURED PROGRAMMING LANGUAGE
IN C
Instructor: Salim Shadman
Ankur
Date: 25 April 2025
2.
04/22/2025 2
WHAT ISA STRING?
In C programming, a string is not a distinct data type like in
Python or Java.
It is an array of characters that ends with a null character '0'
which marks the end of the string.
In C, a string is an array of characters ending with '0'
No dedicated string data type in C
Used with character arrays like: char str[] = "Hello";
3.
04/22/2025 3
Why is'0' important?
It tells C functions like printf() or strlen() where the string
ends.
Without it, C would keep reading memory past the
string, leading to errors.
Example:
char greeting[] = "Hello";
This is stored in memory as:
Index 0 1 2 3 4 5
Value H e l l o 0
4.
04/22/2025 4
DECLARING STRINGS
Example1: Fixed size without initialization
char str[20]; Declares a string with max length 19.
→
This reserves space for 20 characters, enough for 19 characters + '0’.
Example 2: With Initialization
char name[] = "John"; Initializes and auto-adds '0'.
→
The compiler automatically adds the null character.
⚠️Important: If you write:
char str[] = {'H', 'i'}; Not valid string (no '0').
→
There is no null terminator, so it’s not a valid string for C string functions.
5.
04/22/2025 5
STRING INPUT/OUTPUT
⚠️scanf()Limitation
scanf("%s", str); Stops at space.
→
• It cannot read strings with spaces.
• For example, typing Open AI will store only Open.
gets(str); Reads spaces but unsafe (deprecated).
→
fgets(str, sizeof(str), stdin); Safe, reads full line
→
✅ Better: Use fgets()
fgets(str, sizeof(str), stdin);
• Reads spaces.
• Automatically stops at newline or max size.
Best practice for string input = fgets()
6.
04/22/2025 6
STRING HANDLINGFUNCTIONS
strlen(s): Returns length of string (excluding '0’).
char msg[] = "Hello";
int len = strlen(msg); // 5 (not 6!)
strcpy(dest, src): Copies string.
char a[20], b[] = "World";
strcpy(a, b); // a = "World“
strcmp(s1, s2): Compares strings.
strcmp("abc", "abc") 0
→
strcmp("abc", "abd") -1
→
strcmp("abd", "abc") 1
→
🔹 Returns 0 if equal, negative if a < b, positive if a > b.
7.
04/22/2025 7
STRING HANDLINGFUNCTIONS
strcat(dest, src): Appends strings.
char a[20] = "Hello";
char b[] = "World";
strcat(a, b); // a = "HelloWorld"
strstr(haystack, needle): Finds substring.
char text[] = "Welcome to C programming";
char word[] = "C";
char *result = strstr(text, word);
if (result != NULL)
printf("Found at position: %ldn", result - text);
else
printf("Not foundn");
8.
04/22/2025 8
STRING LENGTH(STRLEN())
strlen() – Get the Length of a String
Syntax:
size_t strlen(const char *str);
Counts the number of characters before the null terminator 0.
Does not include 0 in the length.
Returns a value of type size_t (usually an unsigned int).
✅ Example:
#include <stdio.h>
#include <string.h>
int main()
{
char name[] = "Programming";
int len = strlen(name);
printf("Length of the string is: %dn", len);
return 0;
}
Output: Length of the string is: 11
9.
04/22/2025 9
STRING COPY(STRCPY())
strcpy() – Copy One String to Another
Syntax:
char *strcpy(char *dest, const char *src);
Copies the content of src (including 0) into dest.
dest must have enough space to hold the copied string.
The return value is dest
✅ Example:
#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "Learn C";
char destination[20]; // Make sure it's big enough
strcpy(destination, source);
printf("Copied string: %sn", destination);
return 0;
}
Output: Copied string: Learn
•.
10.
04/22/2025 10
STRING CONCATENATION(STRCAT())
strcat() – Concatenate Two Strings
Syntax:
char *strcat(char *dest, const char *src);
Appends the source string (src) to the destination string (dest).
The resulting string is stored in dest.
dest must have enough space to hold the result.
✅ Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50] = "Hello, ";
char str2[] = "world!";
strcat(str1, str2);
printf("Concatenated string: %sn", str1);
return 0;
}
Output: Concatenated string: Hello, world!
•.
11.
04/22/2025 11
STRING COMPARISON(STRCMP())
strcmp() – Compare Two Strings
Syntax:
int strcmp(const char *str1, const char *str2);
Compares str1 and str2 character by character.
Returns:
0 if both strings are equal.
Negative value if str1 < str2.
Positive value if str1 > str2.
✅ Example:
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "apple";
char b[] = "banana";
int result = strcmp(a, b);
if (result == 0)
printf("Strings are equaln");
else if (result < 0)
printf("'%s' comes before '%s'n", a, b);
else
printf("'%s' comes after '%s'n", a, b);
return 0;
}
Output: 'apple' comes before 'banana'
•.
12.
04/22/2025 12
STRING COMPARISON(STRCMP())
•.
⚠️Common Mistake:
if (a == b) // ❌ Wrong
This compares addresses, not content.
Always use strcmp() for string comparison.
13.
04/22/2025 13
FINDING SUBSTRING(STRSTR())
strstr() – Find a Substring in a String
Syntax:
char *strstr(const char *haystack, const char *needle);
Searches for the first occurrence of needle in haystack.
Returns a pointer to the first match in haystack.
Returns NULL if not found
✅ Example:
#include <stdio.h>
#include <string.h>
int main()
{
char text[] = "Welcome to C programming";
char word[] = "C";
char *result = strstr(text, word);
if (result != NULL)
printf("Found at position: %ldn", result - text);
else
printf("Not foundn"); return 0;
}
Output: Found at position: 11
•.
•.
14.
04/22/2025 14
MANUAL STRINGOPERATIONS
strlen: loop until '0' to count characters.
size_t my_strlen(const char s[]) {
size_t i = 0;
while (s[i] != '0') {
i++;
}
return i;
}
15.
04/22/2025 15
MANUAL STRINGOPERATIONS
strcpy: copy one char at a time until '0'.
char *my_strcpy(char dest[], const char src[]) {
size_t i = 0;
// copy each character, including the terminating null
do {
dest[i] = src[i];
} while (src[i++] != '0');
return dest;
}
16.
04/22/2025 16
MANUAL STRINGOPERATIONS
strcmp: compare character by character.
//lexicographically compare two strings. returns 0 if equal, <0 if s1<s2, >0 if s1>s2
int my_strcmp(const char s1[], const char s2[]) {
size_t i = 0;
// advance until chars differ or one hits '0'
while (s1[i] != '0' && s1[i] == s2[i]) {
i++;
}
// at this point either s1[i] or s2[i] is '0' or they differ
return (unsigned char)s1[i] - (unsigned char)s2[i];
}
17.
04/22/2025 17
MANUAL STRINGOPERATIONS
strcat: append src to the end of dest
char *my_strcat(char dest[], const char src[]) {
size_t i = 0, j = 0;
// find end of dest (i.e. its length)
while (dest[i] != '0') {
i++;
}
// copy src into dest starting at i
do {
dest[i + j] = src[j];
} while (src[j++] != '0');
return dest;
}
18.
04/22/2025 18
MANUAL STRINGOPERATIONS
strstr: Find the first occurrence of needle in haystack. Returns a
pointer into haystack, or NULL if not found
char *my_strstr(char haystack[], const char needle[]) {
size_t hlen = my_strlen(haystack);
size_t nlen = my_strlen(needle);
if (nlen == 0) {
return haystack; // empty needle matches at start
}
for (size_t i = 0; i + nlen <= hlen; i++) {
// check match at position i
size_t j = 0;
while (j < nlen && haystack[i + j] == needle[j]) {
j++;
}
if (j == nlen) {
return &haystack[i];
}
}
return NULL;
}
19.
04/22/2025 19
EXAMPLE PROBLEM:REVERSE A STRING
Use two pointers: start and end.
Swap characters until pointers meet.
Null terminator stays untouched.
void reverse(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
20.
04/22/2025 20
EXAMPLE PROBLEM:CHECK PALINDROME
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;
}
21.
04/22/2025 21
WARNINGS &BEST PRACTICES
Mistake Why It's Bad Fix
Using == to compare
strings
Compares addresses,
not content
Use strcmp()
Forgetting '0'
Causes undefined
behavior
Always terminate
manually
Not checking buffer
overflow
Can crash the program
Use fgets() instead of
gets()
22.
04/22/2025 22
PRACTICE LABTASK
Take two strings as input.
Check if second string is substring of first.
Use strstr() or manual logic.
Print position or 'Not Found'.
23.
04/22/2025 23
SUMMARY
Stringsare null-terminated character arrays.
Use string.h functions for ease.
Manual string manipulation helps in learning C internals.
Always consider safety in input/output.