Unit 3 Part 2
Unit 3 Part 2
INTRODUCTION TO PROGRAMMING
UNIT – 3 PART – 2
Arrays:
Introduction to Strings; string handling functions; Implementation of string
copy and string concatenation without using string library functions.
Introduction to Strings in C
Since C does not have a built-in string data type like some other programming
languages, we work with character arrays (char[]) to create and manipulate
strings. By convention, the end of a C string is marked by a null character ('\0'),
which helps various C library functions recognize where the string ends.
In C, there are several ways to initialize strings. Here’s a list of some common
methods:
This initializes str1 with the characters 'H', 'e', 'l', 'l', 'o', followed by a null
character \0.
The array size will automatically be 6 (5 characters + \0).
Here, str2 is explicitly sized at 10, but only the first 6 slots (H, e, l, l, o, \0)
are used.
The remaining slots are left uninitialized or could be set explicitly.
Here, strcpy copies the content of "Hello" into str6, including the null
terminator.
This is helpful when you want to initialize strings dynamically.
To take a string as input at runtime and print it in C, you can use functions
like scanf, gets (although not recommended due to security risks), or fgets. Here
are some examples:
1. Using scanf
The scanf function can be used with the % s format specifier to read a string
until a whitespace character (space, tab, newline) is encountered.
#include <stdio.h>
int main() {
char str[50]; // Allocate enough space for the string
printf("Enter a string: ");
scanf("% 49s", str); // Limiting input to prevent buffer overflow
printf("You entered: % s\n", str);
return 0;
}
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
Note: scanf with % s stops reading when it encounters a space. So, if the
input is Hello World, only Hello will be read.
2. Using fgets
fgets is safer and allows you to read a full line, including spaces, and specifies a
maximum character limit to avoid buffer overflow.
#include <stdio.h>
int main() {
char str[50]; // Allocate enough space for the string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read a line of text, including spaces
printf("You entered: % s", str);
return 0;
}
Note: fgets includes the newline character \n if there’s space in the array,
so it may appear in the output. You can remove it if needed:
The gets function reads an entire line, including spaces, but it is not safe
because it doesn't limit the input size, which may lead to buffer overflow.
Therefore, gets is not recommended and has been removed in C11.
#include <stdio.h>
int main() {
char str[50]; // Allocate enough space for the string
printf("Enter a string: ");
gets(str); // Not safe, avoid using
printf("You entered: % s\n", str);
return 0;
}
Syntax
int puts(const char *str);
#include <stdio.h>
int main() {
char greeting[] = "Hello, world!";
puts(greeting); // Prints "Hello, world!" followed by a newline
return 0;
}
puts("Hello, C programming!");
With puts: Only strings (or string literals) are allowed, and it
automatically adds a newline.
With printf: It’s more flexible, allowing formatted output with various
data types, but it doesn’t automatically add a newline:
#include <stdio.h>
int main() {
char name[] = "Alice";
// Using puts
puts("Hello, world!");
puts(name); // Prints "Alice" followed by a newline
// Using printf
printf("Hello, % s!\n", name); // Prints formatted output with a newline
return 0;
}
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str); // Calculates length of str
printf("Length of the string: %d\n", length);
return 0;
}
Output:
Explanation:
strcpy copies the contents of one string (source) to another string (destination),
including the null character.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, C Programming!";
char destination[50];
return 0;
}
Output:
Explanation:
strcat appends one string (source) to the end of another string (destination).
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello, ";
char str2[] = "World!";
return 0;
}
Output:
Explanation:
strcat appends str2 to the end of str1. The null character of str1 is replaced,
and the null character is added after the concatenated result.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";
return 0;
}
Output:
Explanation:
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char ch = 'o';
char *result = strchr(str, ch); // Finds first occurrence of 'o'
if (result != NULL) {
printf("Character '% c' found at position: % ld\n", ch, result - str);
} else {
printf("Character '% c' not found.\n", ch);
}
return 0;
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
Output:
Explanation:
strchr returns a pointer to the first occurrence of 'o' in "Hello, World!". The
position is 4 (0-based index).
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char substr[] = "World";
char *result = strstr(str, substr); // Finds first occurrence of "World"
if (result != NULL) {
printf("Substring '%s' found at position: % ld\n", substr, result - str);
} else {
printf("Substring '%s' not found.\n", substr);
}
return 0;
}
Output:
Explanation:
These functions from string.h provide essential operations for working with
strings in C. They allow for length calculation, copying, concatenation,
comparison, and searching within strings.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
int main() {
char source[] = "Hello, world!"; // Source string to be copied
char destination[50]; // Destination string (make sure it's large enough)
int i = 0;
return 0;
}
1. Header File: The program includes the standard input-output header file
<stdio.h> for using the printf function.
2. Main Function: The main() function is the entry point of the program.
3. Source String: A character array source is initialized with the string "Hello,
world!".
4. Destination Array: A character array destination is declared to hold the
copied string. The size should be large enough to accommodate the
source string.
5. Copying Process:
o An integer variable i is initialized to zero.
o A while loop iterates through each character of the source string.
o The loop continues until it encounters the null terminator (\0),
which signifies the end of the string.
o Inside the loop, each character from source[i] is copied to
destination[i], and i is incremented.
6. Null Terminator: After copying all characters, a null terminator is added
to the end of the destination array to mark the end of the string.
7. Output: The program uses printf to display the copied string.
8. Return Statement: The program returns 0 to indicate successful
execution.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
int main() {
char destination[50] = "Hello, "; // Destination string initialized
char source[] = "world!"; // Source string to be concatenated
int i = 0, j = 0;
return 0;
}
1. Header File: The program begins with including <stdio.h> for input-
output operations.
2. Main Function: The main() function serves as the starting point of
execution.
3. Destination String: A character array destination is initialized with the
string "Hello, ", which will hold the final concatenated string.
4. Source String: A character array source is initialized with the string
"world!", which will be appended to the destination.
5. Finding the End of Destination:
o Two integer variables i and j are initialized to zero.
o A while loop iterates over the destination string to find its null
terminator (\0), which indicates where to start appending the source
string.
6. Concatenation Process:
o Another while loop iterates through the source string until its null
terminator is reached.
o Inside the loop, each character from source[j] is appended to
destination[i], and both indices i and j are incremented.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC
int main() {
char str[] = "Hello, world!"; // Input string
int length = 0; // Variable to hold the length
printf("Length of the string: %d\n", length); // Print the length of the string
return 0;
}
1. Header File: The program includes the standard input-output header file
<stdio.h> for using the printf function.
2. Main Function: The main() function serves as the entry point for the
program.
3. Input String: A character array str is initialized with the string "Hello,
world!".
4. Length Variable: An integer variable length is declared and initialized to
zero. This variable will be used to count the number of characters in the
string.
5. Length Calculation:
o A while loop is used to iterate through the characters of the string.
o The loop continues until the null terminator (\0) is encountered,
which indicates the end of the string.
o Inside the loop, the length variable is incremented for each
character found.
6. Output: After the loop, the program uses printf to display the calculated
length of the string.
7. Return Statement: The program returns 0 to indicate successful
execution.