SlideShare a Scribd company logo
Lecture_on_string_manipulation_functions.pptx
Reading a String as Input from the Terminal in C
scanf()
Syntax: scanf("%s", str);
● Description: Reads a word or sequence of characters (no spaces).
● Drawbacks: Stops input at whitespace, doesn't handle spaces.
gets() (Deprecated)
Syntax: gets(str);
● Description:
Reads an entire
line including
spaces until
newline.
● Drawbacks:
fgets()
Syntax: fgets(str, sizeof(str), stdin);
● Description: Safely reads a line, including spaces, and can handle buffer
size.
● Benefits: Prevents buffer overflow.
● Drawbacks: Includes the newline character at the end of the string.
getchar() (Character by Character)
Syntax:
char ch;
ch = getchar();
● Description: Reads input one
character at a time.
● Benefits: Allows character-level
control.
● Drawbacks: Inefficient for
longer strings.
Comparison:
● scanf(): Fast, but stops at whitespace.
● fgets(): Safe for large strings and includes spaces.
● getchar(): Useful for reading character-by-
character.
● gets(): Avoid using, deprecated due to security
risks.
Suppressing Input in scanf()
Command
Purpose: To skip certain parts of the input or suppress values that do not need
to be stored.
How to Suppress Input: Use * (asterisk) in the scanf() format specifier to
suppress input without assigning it to a variable.
Syntax:
scanf("format_specifier", &variable);
scanf("%*format_specifier", ...); // Suppresses input
Example 1: Suppressing a Specific Input
int age;
scanf("%*s %d", &age);
● Input: John 25
● Explanation:
○ The %*s skips the string (John).
○ Only the integer (25) is stored in age.
Example 2: Ignoring Multiple Inputs
scanf("%*d %*d %d", &num);
● Input: 12 34 56
● Explanation:
○ The first two integers are ignored (12 and 34).
○ Only the third integer (56) is stored in num.
Common Use Cases:
● Ignoring unwanted data in the input.
● Parsing specific fields while ignoring others in formatted input.
Key Points:
● * in scanf(): The asterisk suppresses input, preventing storage.
● Useful when you want to skip certain data without needing to assign
it to a variable.
Suppressing Input Using Scanset in scanf()
A scanset is a set of characters specified within square brackets [] that scanf()
can use to control what characters to accept or ignore during input.
Syntax: scanf("%[character_set]", variable);
● Reads only the characters specified in the scanset.
To Suppress Input Using Scanset, add the * modifier:
scanf("%*[character_set]");
Example: Suppressing Vowels
char str[100];
scanf("%*[aeiou] %s", str);
● Input: aeiou Hello
● Explanation:
○ %*[aeiou]: Skips any vowels at the start of the input.
○ %s: Reads the next word (Hello) and stores it in str.
Example 2: Suppressing Digits
char name[50];
scanf("%*[0-9] %s", name);
● Input: 12345 John
● Explanation:
○ %*[0-9]: Skips any digits at the start of the input.
○ %s: Reads the word (John) and stores it in name.
Key Points:
● Scanset allows specifying character sets to read or skip.
● Suppress Input with *: Add * before the scanset to skip those
characters.
● Useful for skipping unwanted characters while parsing structured
input.
sscanf() Function in
C
Syntax: int sscanf(const char *str, const char *format, ...);
Description:
● The sscanf() function reads formatted input from a string rather than standard input (like
scanf()).
● It parses the string according to the specified format and stores the values in
corresponding variables.
Parameters:
1. str: The input string from which data is extracted.
2. format: A format string containing specifiers to indicate the type of input (e.g., %d for
integers, %s
for strings).
3. ...: The list of variables where the extracted data will be stored.
Return Value:
● Returns the number of input items successfully matched and assigned.
● Returns EOF if an error occurs or if the end of the string is reached before any values
Example:
char str[] = "42 Hello";
int num;
char word[20];
sscanf(str, "%d %s", &num, word);
printf("Number: %dn", num);
printf("Word: %sn", word);
Key Points:
// Output: Number: 42
// Output: Word: Hello
● sscanf() reads data from a string instead of standard input
(terminal).
● It’s useful for parsing structured data in strings.
● The format specifiers are the same as scanf().
Example 2: Parsing Multiple Values
char input[] = "123 John 45.67";
int id;
char name[20];
float score;
sscanf(input,
"%d %s %f",
&id, name,
&score);
printf("ID:
%d, Name: %s,
Score: %.2f
n", id, name,
score);
Writing Strings
printf() Function
Syntax: int printf(const char *format, ...);
Description:
● The printf() function prints formatted output to the terminal.
● The format string specifies how the data should be displayed, with placeholders for
variables.
Common Format Specifiers:
● %d – Integer
● %f – Floating-point number
● %c – Character
● %s – String
puts()
Function
Syntax:
int puts(const char *str);
Description:
● The puts() function prints a string followed by a newline character to the
terminal.
● It automatically appends a newline (n) at the end.
Example:
puts("Hello, World!"); // Output: Hello, World!n
Advantages:
● Simpler than printf() for printing strings.
● Automatically adds a newline.
Return Value:
● Returns a non-negative value on success.
● Returns EOF on error.
putchar()
Function
Syntax:
int putchar(int char);
Description:
● The putchar() function prints a single character to the
terminal.
Example:
putchar('A'); // Output: A
putchar('n'); // Output: (newline)
Return Value:
● Returns the character written as an unsigned
char.
● Returns EOF on error.
Comparison of Functions:
● printf(): Flexible, prints formatted output (multiple
types).
● puts(): Simplified for strings, appends newline.
● putchar(): Used for printing single characters.
Strlen function
Syntax: size_t strlen(const char *str);
Description: Returns the length of the string str, excluding the null terminator
(0).
Example: char str[] = "Hello, World!";
printf("Length: %zu", strlen(str)); // Output: 13
Benefits:
● Simple to use for finding string length.
● Efficient as it only traverses the string once.
Drawbacks:
● Requires a null-terminated string.
● Cannot detect the size of arrays, only the number of
characters before 0.
strcpy – String Copy
Function
Syntax:
char *strcpy(char *dest, const char *src);
Description: Copies the string src into dest. The destination must have enough
space to hold the source string, including the null terminator.
Example:
char src[] = "Copy me";
char dest[20];
strcpy(dest, src);
printf("%s",
dest); // Output:
Copy me
Drawbacks: No bounds
strcmp – String Comparison
Function
Syntax:
int strcmp(const char *str1, const char *str2);
Description: Compares two strings lexicographically. Returns:
● 0 if both strings are equal.
● A negative value if str1 is less than str2.
● A positive value if str1 is greater than str2.
Example:
char str1[] = "apple";
char str2[] = "banana";
int result =
strcmp(str1, str2); //
Output: negative value
Benefits:
● Useful for string
comparison in sorting
strcat – String Concatenation Function
Syntax: char *strcat(char *dest, const char *src);
● Description: Appends the src string to the dest string, overwriting the null character at
the end of dest.
Example:
char dest[20] = "Hello";
strcat(dest, " World");
printf("%s", dest); // Output: Hello World
● Benefits: Simple string concatenation.
● Drawbacks: No bounds checking; can cause buffer overflow if dest is not large enough.
strncat – Safe String Concatenation
Syntax: char *strncat(char *dest, const char *src, size_t n);
Description: Appends at most n characters from src to dest, ensuring a null
terminator.
Example:
char dest[20] = "Hello";
strncat(dest, " World", 3);
printf("%s", dest); // Output: Hello Wo
Benefits: Adds a layer of safety by limiting the
number of characters appended.
Drawbacks: Still requires care with buffer sizes.
strchr – String Character Search
Syntax: char *strchr(const char *str, int c);
Description: Searches for the first occurrence of the character c in the string str
and returns a pointer to it, or NULL if not found.
Example:
char str[] = "Find me!";
char *ptr = strchr(str, 'm');
printf("%s", ptr); // Output: me!
Benefits: Fast character search within
strings.
Drawbacks: Returns NULL if the character is not found, which can lead to null
pointer dereferencing if unchecked.
strstr – Substring Search
Syntax: char *strstr(const char *haystack, const char *needle);
Description: Finds the first occurrence of the substring needle in the string haystack
and returns a pointer to it, or NULL if not found.
Example:
char str[] = "Find the needle in the haystack";
char *ptr = strstr(str, "needle");
printf("%s", ptr); // Output: needle in the haystack
Benefits: Useful for substring searches.
Drawbacks: Case-sensitive; returns NULL if no match is found.
1. Write a program to read the names of n students of a class.
2. Write a program to sort names of students.
3. Write a program to read a sentence. Then count the number of words
in the sentence
4. Write a program to enter a text that contains multiple lines. Display the n
lines of text starting from the mth line.
#include
<stdio.h> int
main() {
char str1[10] =
"Hello"; char str2[10];
str2 = str1; // Copying
string printf("String 2: %s
n", str2); return 0;
}
Find the error
Answer:
Error: Strings in C cannot be assigned using the = operator. This will result in a compilation error because
arrays cannot be directly assigned.
Fix: Use strcpy() from the <string.h> library to copy strings.
Corrected Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "Hello";
char str2[10];
strcpy(str2, str1); // Use strcpy to copy
strings printf("String 2: %sn", str2);
return 0;
}
#include <stdio.h>
int main()
{ char
str[5];
printf("Enter a string: ");
scanf("%s", str); // Input
string printf("You entered:
%sn", str); return 0;
}
Error: The size of str is too small to handle user input. If the user enters more than 4 characters, it will
cause buffer overflow.
Fix: Either increase the size of the array, or limit the number of characters to be read using %Ns where
N is the maximum number of characters.
Corrected Code:
#include <stdio.h>
int main() {
char str[100]; // Increase buffer size
printf("Enter a string: ");
scanf("%99s", str); // Limit input to prevent
overflow printf("You entered: %sn", str);
return 0;
}
#include <stdio.h>
int main() {
char *str = "Hello";
str[0] = 'h'; // Trying to modify string
literal printf("%sn", str);
return 0;
}
Error:
● String literals are stored in read-only memory in most systems, so modifying them results in undefined
behavior.
Fix:
● Use an array to store the string if you need to modify it.
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] =
"World"; if (str1 ==
str2) {
printf("Strings
are equaln");
} else {
printf("Strings
are not equaln");
}
return 0;
}
Error:
● You cannot compare strings using == in C. This compares the
addresses of the strings, not the content.
Fix:
● Use the strcmp() function from the <string.h> library to
compare the content of the strings.
#include <stdio.h>
int main() {
char str[6] =
"Hello"; printf("%s
n", str); return 0;
}
Error:
● The size of str is too small. The string "Hello" has 5 characters,
but C strings require an additional byte for the null terminator (0).
Fix:
● Increase the size of the array to accommodate the null terminator.
#include
<stdio.h>
int main() {
char str[] = "Hello";
printf("%cn", str[5]); // Printing the character at
index 5 return 0;
}
Error:
● Index 5 in the string "Hello" is the null terminator (0). It is technically valid but may not produce the expected
output.
Fix:
● If you want to print the last character, use index 4.
#include <stdio.h>
int main()
{ char
str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %sn", str);
return 0;
}
Error: If the user enters a string with spaces, scanf() will stop reading
at the first space, so only the first word will be stored.
Fix: Use fgets() to read the entire line, including spaces.
Find the error in the following codes:
#include <stdio.h>
int main()
{ char
str[10];
gets(str); // Input string
printf("You entered: %sn",
str); return 0;
}
Answer:
Error:
● The function gets() is dangerous and should not be used because it
does not perform bounds checking, leading to potential buffer
overflow.
Fix:
● Use fgets() instead of gets() to avoid buffer overflow.

More Related Content

PPT
Strings
PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
PPT
Chapterabcdefghijklmnopqrdstuvwxydanniipo
PPT
THE FORMAT AND USAGE OF STRINGS IN C.PPT
PPTX
ARRAY's in C Programming Language PPTX.
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
PDF
Strings in c mrs.sowmya jyothi
PPTX
Computer Programming Utilities the subject of BE first year students, and thi...
Strings
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Chapterabcdefghijklmnopqrdstuvwxydanniipo
THE FORMAT AND USAGE OF STRINGS IN C.PPT
ARRAY's in C Programming Language PPTX.
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
Strings in c mrs.sowmya jyothi
Computer Programming Utilities the subject of BE first year students, and thi...

Similar to Lecture_on_string_manipulation_functions.pptx (20)

PDF
String notes
PDF
Character Array and String
PPTX
C programming - String
PPTX
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
DOCX
C Programming Strings.docx
PPTX
Managing I/O & String function in C
PPTX
CSE 1102 - Lecture_7 - Strings_in_C.pptx
PDF
[ITP - Lecture 17] Strings in C/C++
PPT
String & its application
PPTX
Handling of character strings C programming
PPTX
programming for problem solving using C-STRINGSc
PPTX
Btech i pic u-4 function, storage class and array and strings
PDF
Functions torage class and array and strings-
PPTX
function, storage class and array and strings
PPTX
String_Slide.pptxStructure.pptxStructure.pptxStructure.pptxStructure.pptx
PPTX
pps unit 3.pptx
PPTX
Diploma ii cfpc u-4 function, storage class and array and strings
DOCX
Array &strings
PPTX
Mcai pic u 4 function, storage class and array and strings
PDF
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 6.pdf
String notes
Character Array and String
C programming - String
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
C Programming Strings.docx
Managing I/O & String function in C
CSE 1102 - Lecture_7 - Strings_in_C.pptx
[ITP - Lecture 17] Strings in C/C++
String & its application
Handling of character strings C programming
programming for problem solving using C-STRINGSc
Btech i pic u-4 function, storage class and array and strings
Functions torage class and array and strings-
function, storage class and array and strings
String_Slide.pptxStructure.pptxStructure.pptxStructure.pptxStructure.pptx
pps unit 3.pptx
Diploma ii cfpc u-4 function, storage class and array and strings
Array &strings
Mcai pic u 4 function, storage class and array and strings
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 6.pdf
Ad

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
master seminar digital applications in india
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Lesson notes of climatology university.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Weekly quiz Compilation Jan -July 25.pdf
Cell Types and Its function , kingdom of life
master seminar digital applications in india
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
Computing-Curriculum for Schools in Ghana
2.FourierTransform-ShortQuestionswithAnswers.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Classroom Observation Tools for Teachers
Lesson notes of climatology university.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

Lecture_on_string_manipulation_functions.pptx

  • 2. Reading a String as Input from the Terminal in C scanf() Syntax: scanf("%s", str); ● Description: Reads a word or sequence of characters (no spaces). ● Drawbacks: Stops input at whitespace, doesn't handle spaces. gets() (Deprecated) Syntax: gets(str); ● Description: Reads an entire line including spaces until newline. ● Drawbacks:
  • 3. fgets() Syntax: fgets(str, sizeof(str), stdin); ● Description: Safely reads a line, including spaces, and can handle buffer size. ● Benefits: Prevents buffer overflow. ● Drawbacks: Includes the newline character at the end of the string. getchar() (Character by Character) Syntax: char ch; ch = getchar(); ● Description: Reads input one character at a time. ● Benefits: Allows character-level control. ● Drawbacks: Inefficient for longer strings.
  • 4. Comparison: ● scanf(): Fast, but stops at whitespace. ● fgets(): Safe for large strings and includes spaces. ● getchar(): Useful for reading character-by- character. ● gets(): Avoid using, deprecated due to security risks.
  • 5. Suppressing Input in scanf() Command Purpose: To skip certain parts of the input or suppress values that do not need to be stored. How to Suppress Input: Use * (asterisk) in the scanf() format specifier to suppress input without assigning it to a variable. Syntax: scanf("format_specifier", &variable); scanf("%*format_specifier", ...); // Suppresses input Example 1: Suppressing a Specific Input int age; scanf("%*s %d", &age); ● Input: John 25 ● Explanation: ○ The %*s skips the string (John). ○ Only the integer (25) is stored in age.
  • 6. Example 2: Ignoring Multiple Inputs scanf("%*d %*d %d", &num); ● Input: 12 34 56 ● Explanation: ○ The first two integers are ignored (12 and 34). ○ Only the third integer (56) is stored in num. Common Use Cases: ● Ignoring unwanted data in the input. ● Parsing specific fields while ignoring others in formatted input. Key Points: ● * in scanf(): The asterisk suppresses input, preventing storage. ● Useful when you want to skip certain data without needing to assign it to a variable.
  • 7. Suppressing Input Using Scanset in scanf() A scanset is a set of characters specified within square brackets [] that scanf() can use to control what characters to accept or ignore during input. Syntax: scanf("%[character_set]", variable); ● Reads only the characters specified in the scanset. To Suppress Input Using Scanset, add the * modifier: scanf("%*[character_set]"); Example: Suppressing Vowels char str[100]; scanf("%*[aeiou] %s", str); ● Input: aeiou Hello ● Explanation: ○ %*[aeiou]: Skips any vowels at the start of the input. ○ %s: Reads the next word (Hello) and stores it in str.
  • 8. Example 2: Suppressing Digits char name[50]; scanf("%*[0-9] %s", name); ● Input: 12345 John ● Explanation: ○ %*[0-9]: Skips any digits at the start of the input. ○ %s: Reads the word (John) and stores it in name. Key Points: ● Scanset allows specifying character sets to read or skip. ● Suppress Input with *: Add * before the scanset to skip those characters. ● Useful for skipping unwanted characters while parsing structured input.
  • 9. sscanf() Function in C Syntax: int sscanf(const char *str, const char *format, ...); Description: ● The sscanf() function reads formatted input from a string rather than standard input (like scanf()). ● It parses the string according to the specified format and stores the values in corresponding variables. Parameters: 1. str: The input string from which data is extracted. 2. format: A format string containing specifiers to indicate the type of input (e.g., %d for integers, %s for strings). 3. ...: The list of variables where the extracted data will be stored. Return Value: ● Returns the number of input items successfully matched and assigned. ● Returns EOF if an error occurs or if the end of the string is reached before any values
  • 10. Example: char str[] = "42 Hello"; int num; char word[20]; sscanf(str, "%d %s", &num, word); printf("Number: %dn", num); printf("Word: %sn", word); Key Points: // Output: Number: 42 // Output: Word: Hello ● sscanf() reads data from a string instead of standard input (terminal). ● It’s useful for parsing structured data in strings. ● The format specifiers are the same as scanf().
  • 11. Example 2: Parsing Multiple Values char input[] = "123 John 45.67"; int id; char name[20]; float score; sscanf(input, "%d %s %f", &id, name, &score); printf("ID: %d, Name: %s, Score: %.2f n", id, name, score);
  • 12. Writing Strings printf() Function Syntax: int printf(const char *format, ...); Description: ● The printf() function prints formatted output to the terminal. ● The format string specifies how the data should be displayed, with placeholders for variables. Common Format Specifiers: ● %d – Integer ● %f – Floating-point number ● %c – Character ● %s – String
  • 13. puts() Function Syntax: int puts(const char *str); Description: ● The puts() function prints a string followed by a newline character to the terminal. ● It automatically appends a newline (n) at the end. Example: puts("Hello, World!"); // Output: Hello, World!n Advantages: ● Simpler than printf() for printing strings. ● Automatically adds a newline. Return Value: ● Returns a non-negative value on success. ● Returns EOF on error.
  • 14. putchar() Function Syntax: int putchar(int char); Description: ● The putchar() function prints a single character to the terminal. Example: putchar('A'); // Output: A putchar('n'); // Output: (newline) Return Value: ● Returns the character written as an unsigned char. ● Returns EOF on error.
  • 15. Comparison of Functions: ● printf(): Flexible, prints formatted output (multiple types). ● puts(): Simplified for strings, appends newline. ● putchar(): Used for printing single characters.
  • 16. Strlen function Syntax: size_t strlen(const char *str); Description: Returns the length of the string str, excluding the null terminator (0). Example: char str[] = "Hello, World!"; printf("Length: %zu", strlen(str)); // Output: 13 Benefits: ● Simple to use for finding string length. ● Efficient as it only traverses the string once. Drawbacks: ● Requires a null-terminated string. ● Cannot detect the size of arrays, only the number of characters before 0.
  • 17. strcpy – String Copy Function Syntax: char *strcpy(char *dest, const char *src); Description: Copies the string src into dest. The destination must have enough space to hold the source string, including the null terminator. Example: char src[] = "Copy me"; char dest[20]; strcpy(dest, src); printf("%s", dest); // Output: Copy me Drawbacks: No bounds
  • 18. strcmp – String Comparison Function Syntax: int strcmp(const char *str1, const char *str2); Description: Compares two strings lexicographically. Returns: ● 0 if both strings are equal. ● A negative value if str1 is less than str2. ● A positive value if str1 is greater than str2. Example: char str1[] = "apple"; char str2[] = "banana"; int result = strcmp(str1, str2); // Output: negative value Benefits: ● Useful for string comparison in sorting
  • 19. strcat – String Concatenation Function Syntax: char *strcat(char *dest, const char *src); ● Description: Appends the src string to the dest string, overwriting the null character at the end of dest. Example: char dest[20] = "Hello"; strcat(dest, " World"); printf("%s", dest); // Output: Hello World ● Benefits: Simple string concatenation. ● Drawbacks: No bounds checking; can cause buffer overflow if dest is not large enough.
  • 20. strncat – Safe String Concatenation Syntax: char *strncat(char *dest, const char *src, size_t n); Description: Appends at most n characters from src to dest, ensuring a null terminator. Example: char dest[20] = "Hello"; strncat(dest, " World", 3); printf("%s", dest); // Output: Hello Wo Benefits: Adds a layer of safety by limiting the number of characters appended. Drawbacks: Still requires care with buffer sizes.
  • 21. strchr – String Character Search Syntax: char *strchr(const char *str, int c); Description: Searches for the first occurrence of the character c in the string str and returns a pointer to it, or NULL if not found. Example: char str[] = "Find me!"; char *ptr = strchr(str, 'm'); printf("%s", ptr); // Output: me! Benefits: Fast character search within strings. Drawbacks: Returns NULL if the character is not found, which can lead to null pointer dereferencing if unchecked.
  • 22. strstr – Substring Search Syntax: char *strstr(const char *haystack, const char *needle); Description: Finds the first occurrence of the substring needle in the string haystack and returns a pointer to it, or NULL if not found. Example: char str[] = "Find the needle in the haystack"; char *ptr = strstr(str, "needle"); printf("%s", ptr); // Output: needle in the haystack Benefits: Useful for substring searches. Drawbacks: Case-sensitive; returns NULL if no match is found.
  • 23. 1. Write a program to read the names of n students of a class. 2. Write a program to sort names of students. 3. Write a program to read a sentence. Then count the number of words in the sentence 4. Write a program to enter a text that contains multiple lines. Display the n lines of text starting from the mth line.
  • 24. #include <stdio.h> int main() { char str1[10] = "Hello"; char str2[10]; str2 = str1; // Copying string printf("String 2: %s n", str2); return 0; } Find the error
  • 25. Answer: Error: Strings in C cannot be assigned using the = operator. This will result in a compilation error because arrays cannot be directly assigned. Fix: Use strcpy() from the <string.h> library to copy strings. Corrected Code: #include <stdio.h> #include <string.h> int main() { char str1[10] = "Hello"; char str2[10]; strcpy(str2, str1); // Use strcpy to copy strings printf("String 2: %sn", str2); return 0; }
  • 26. #include <stdio.h> int main() { char str[5]; printf("Enter a string: "); scanf("%s", str); // Input string printf("You entered: %sn", str); return 0; }
  • 27. Error: The size of str is too small to handle user input. If the user enters more than 4 characters, it will cause buffer overflow. Fix: Either increase the size of the array, or limit the number of characters to be read using %Ns where N is the maximum number of characters. Corrected Code: #include <stdio.h> int main() { char str[100]; // Increase buffer size printf("Enter a string: "); scanf("%99s", str); // Limit input to prevent overflow printf("You entered: %sn", str); return 0; }
  • 28. #include <stdio.h> int main() { char *str = "Hello"; str[0] = 'h'; // Trying to modify string literal printf("%sn", str); return 0; }
  • 29. Error: ● String literals are stored in read-only memory in most systems, so modifying them results in undefined behavior. Fix: ● Use an array to store the string if you need to modify it.
  • 30. #include <stdio.h> int main() { char str1[] = "Hello"; char str2[] = "World"; if (str1 == str2) { printf("Strings are equaln"); } else { printf("Strings are not equaln"); } return 0; }
  • 31. Error: ● You cannot compare strings using == in C. This compares the addresses of the strings, not the content. Fix: ● Use the strcmp() function from the <string.h> library to compare the content of the strings.
  • 32. #include <stdio.h> int main() { char str[6] = "Hello"; printf("%s n", str); return 0; }
  • 33. Error: ● The size of str is too small. The string "Hello" has 5 characters, but C strings require an additional byte for the null terminator (0). Fix: ● Increase the size of the array to accommodate the null terminator.
  • 34. #include <stdio.h> int main() { char str[] = "Hello"; printf("%cn", str[5]); // Printing the character at index 5 return 0; }
  • 35. Error: ● Index 5 in the string "Hello" is the null terminator (0). It is technically valid but may not produce the expected output. Fix: ● If you want to print the last character, use index 4.
  • 36. #include <stdio.h> int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); printf("You entered: %sn", str); return 0; }
  • 37. Error: If the user enters a string with spaces, scanf() will stop reading at the first space, so only the first word will be stored. Fix: Use fgets() to read the entire line, including spaces.
  • 38. Find the error in the following codes: #include <stdio.h> int main() { char str[10]; gets(str); // Input string printf("You entered: %sn", str); return 0; }
  • 39. Answer: Error: ● The function gets() is dangerous and should not be used because it does not perform bounds checking, leading to potential buffer overflow. Fix: ● Use fgets() instead of gets() to avoid buffer overflow.