0% found this document useful (0 votes)
3 views32 pages

07 - String

Strings in C are character arrays terminated by a null character, with various functions available for handling them, such as strlen(), strcpy(), strcat(), and strcmp(). Proper buffer management is crucial to avoid overflow, and safer alternatives like fgets() are recommended over gets(). Additional functions for string manipulation include case-insensitive comparison and partial concatenation.

Uploaded by

krgoudanamashya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

07 - String

Strings in C are character arrays terminated by a null character, with various functions available for handling them, such as strlen(), strcpy(), strcat(), and strcmp(). Proper buffer management is crucial to avoid overflow, and safer alternatives like fgets() are recommended over gets(). Additional functions for string manipulation include case-insensitive comparison and partial concatenation.

Uploaded by

krgoudanamashya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Strings in C

• Strings in C are group of characters, digits, and


symbols enclosed in quotation marks or
simply we can say the string is declared as a
“character array”.
• A string is a one-dimensional array of
characters terminated by a null character '\0',
which has the decimal value 0.
• Include header file: string.h
Example of String Declaration
• char name[] = {'v','i','j','a','y','\0'};

• There is a difference between a character stored in


memory and a single character string stored in a memory.
• The character requires only one byte whereas the single
character string requires two bytes (one byte for the
character and other byte for the delimiter).
String Handling Functions
1. strlen() - Finds length of string
2. strcpy() - Copies one string to another
3. strcat() - Concatenates two strings
4. strcmp() - Compares two strings
strlen() Function
• Used to find the length of a string.
• Example:
int n;
char st[20] = 'Bangalore';
n = strlen(st);
#include <stdio.h>
#include <string.h>

int main() {
char str[50];
int length;

printf("Enter a string: ");


gets(str); // safer alternative: fgets(str, sizeof(str), stdin);

length = strlen(str);

printf("Length of the string is: %d\n", length);


return 0;
}

Explanation:
strlen() counts all characters until it encounters the null terminator '\0'
strcpy() Function
• Copies one string to another.
• Example:
char city[15];
strcpy(city, 'BANGALORE');
#include <stdio.h>
#include <string.h>

int main() {
char source[50], destination[50];

printf("Enter the source string: ");


gets(source);

strcpy(destination, source);

printf("Copied string: %s\n", destination);


return 0;
}

Explanation:
strcpy(destination, source) copies the source string including
'\0' to the destination.
strcat() Function
• Joins two strings (concatenation).
• Example:
char city[20]='BANGALORE';
char pin[8]='-560001';
strcat(city,pin);
#include <stdio.h>
#include <string.h>

int main() {
char first[50], second[50];

printf("Enter the first string: ");


gets(first);
printf("Enter the second string: ");
gets(second);

strcat(first, second);

printf("After concatenation: %s\n", first);


return 0;
}

Explanation:
strcat(first, second) appends second to the end of first and adds
a null terminator.
strcmp() Function
• Compares two strings.
• Returns 0 if identical, otherwise returns ASCII
difference.
#include <stdio.h>
#include <string.h> Explanation:
strcmp() compares characters’ ASCII values:
int main() { •Returns 0 → strings iden cal
char str1[50], str2[50]; •Returns posi ve → first string greater
int result; •Returns nega ve → second string greater

printf("Enter first string: ");


gets(str1);
printf("Enter second string: ");
gets(str2);

result = strcmp(str1, str2);

if (result == 0)
printf("Strings are equal.\n");
else if (result > 0)
printf("\"%s\" is greater than \"%s\".\n", str1, str2);
else
printf("\"%s\" is smaller than \"%s\".\n", str1, str2);

return 0;
}
Reading and Writing Strings
• Using scanf(): scanf('%s', string);
• Using gets(): gets(string);
• Safer Alternative
#include <stdio.h>

int main() {
char name[50];

printf("Enter your name: ");


scanf("%s", name); // reads until space or newline

printf("Hello, %s\n", name);


return 0;
}

Explanation:
•scanf("%s", name); reads a single word (no spaces).
•Stops reading when it finds whitespace.
#include <stdio.h>

int main() {
char sentence[100];

printf("Enter a sentence: ");


gets(sentence); // reads the entire line (including spaces)

printf("You entered: %s\n", sentence);


return 0;
}

Explanation:
•gets() reads input including spaces until Enter is pressed.
•But it is unsafe (can overflow the buffer).
Buffer Size
• A buffer’s size defines how many characters it can hold, including the null
terminator '\0'.
• Example: char name[10];

This array can hold:


9 visible characters, plus
1 null terminator '\0'.
So, entering "COMPUTER" (8 letters) fits safely.
Entering "PROGRAMMING" (11 letters) will exceed the buffer.

Buffer Overflow
• Buffer overflow occurs when data is written beyond the allocated space in
memory.
• Example:
char str[5];
gets(str); // dangerous if user types more than 4 characters

If the user enters "HELLO", that’s 6 bytes (H E L L O \0)


but only 5 bytes were allocated.
The extra byte overwrites adjacent memory.
Safer Modern Alternative (Recommended): fgets()

#include <stdio.h>

int main() {
char sentence[100];

printf("Enter a sentence: ");


fgets(sentence, sizeof(sentence), stdin); // safe version

printf("You entered: %s\n", sentence);


return 0;
}

Explanation:
•fgets() limits the number of characters read to the buffer size.
•Always safer than gets().

fgets() was designed to: (ANSI C Standard (1989))


•Limit input length (reads at most n - 1 characters).
•Automatically add the null terminator '\0'.
•Work on any input stream, not just stdin.
This made it a modern and portable replacement for gets().
atoi() Function
• The atoi() function in C converts a string of
digits into an integer value.
• It’s part of the C Standard Library, declared in
stdlib.h
• Example:
char st[10]='24175';
int n=atoi(st);
Palindrome Program
• Program to check if a string is palindrome
using strcmp() and string reversal.
#include <stdio.h>
#include <string.h>

int main() {
char st[20], rst[20];
int i, j;

printf("Enter the string: ");


scanf("%s", st); // reads a single word

i = 0;
j = strlen(st) - 1;

while (j >= 0) { // must be >=, not '='


rst[i] = st[j];
i++;
j--;
}

rst[i] = '\0'; // use correct single quotes

if (strcmp(st, rst) == 0)
printf("%s is a palindrome\n", st);
else
printf("%s is not a palindrome\n", st);

return 0;
}
Character Count Program
• Counts occurrences of a character in a string
using a for loop and strlen().
• Write a C program to count the occurrence of a particular
character in the given string.
#include <stdio.h>
#include <string.h>
int main() {
char st[100], ch;
int count = 0, i, l;
printf("Enter the string: ");
fgets(st, sizeof(st), stdin); // safer than gets()
st[strcspn(st, "\n")] = '\0'; // remove newline from fgets
printf("Which character to count? ");
scanf("%c", &ch);
l = strlen(st);
for (i = 0; i < l; i++) {
if (st[i] == ch)
count++;
}
printf("The character '%c' occurs %d times.\n", ch, count);
return 0;
}
Vowel Count Program
• Counts vowels (A,E,I,O,U) using switch
statement and loop.
#include <stdio.h>
#include <string.h>
#include <ctype.h> // for tolower()
int main() {
char st[200];
int count = 0, i;

printf("Enter a sentence: ");


fgets(st, sizeof(st), stdin); // reads input safely
st[strcspn(st, "\n")] = '\0'; // remove newline

for (i = 0; i < strlen(st); i++) {


switch (tolower((unsigned char)st[i])) { // handle both upper/lower case
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
}
}
printf("Number of vowels in the sentence: %d\n", count);
return 0;
}
String Comparison Program
• Compares two strings alphabetically using
strcmp().
Uppercase Conversion
• Converts lowercase letters to uppercase using
ASCII difference (st[i] = st[i]-32).

Character Decimal Value


A 65
Z 90
a 97
z 122
Additional String Functions
• strupr() – Uppercase
• strlwr() - Lowercase
• strrev() - Reverse
• strncmp() - Compare n chars

Note : strupr() and strlwr(), strrev() are not part of the ISO C standard. It works in
Turbo C, MSVC, and some compilers, but not in GCC.
Case-insensitive Comparison
• strcmpi() is used to compare two strings without
considering case (case-insensitive comparison).
"DELHI" == "delhi" → treated as equal

• Returns –
– 0 if strings are equal (ignoring case).
– A negative value if str1 is alphabetically less than str2.
– A positive value if str1 is greater than str2.
• Key Difference from strcmp() is case insensitivity.
Partial Concatenation
• strncat() is used to concatenate (join) a
specific number of characters from one string
to another.
• Unlike strcat(), it allows you to control how
many characters are appended, preventing
accidental buffer overflow.
• strncat() - Joins first n characters of a string to
another.
#include <stdio.h>
#include <string.h>

int main() {
char s1[20] = "New";
char s2[20] = "Delhi-41";

strncat(s1, s2, 3); // append first 3 characters of s2 to s1

printf("After concatenation: %s\n", s1);


return 0;
}

Parameters:
•destination → The string to which data will be appended.
•source → The string to append from.
•n → The maximum number of characters to copy from source.
Key Notes
• All functions are in <string.h>
• Use proper buffer size to avoid overflow.
Summary
• String operations form the basis for text
handling in C programming.

You might also like