0% found this document useful (0 votes)
11 views11 pages

Unit 3 Part 2

The document provides an introduction to strings in C programming, detailing how to declare, initialize, and manipulate strings using character arrays and various functions. It covers string input methods, the use of the puts function for output, and essential string handling functions from the <string.h> library. Additionally, it includes examples of implementing string copy and concatenation without using library functions.
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)
11 views11 pages

Unit 3 Part 2

The document provides an introduction to strings in C programming, detailing how to declare, initialize, and manipulate strings using character arrays and various functions. It covers string input methods, the use of the puts function for output, and essential string handling functions from the <string.h> library. Additionally, it includes examples of implementing string copy and concatenation without using library functions.
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
You are on page 1/ 11

K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

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

In C, a string is essentially an array of characters terminated by a null


character ('\0'). Strings are a sequence of characters stored in contiguous
memory locations, allowing programmers to manipulate text data efficiently.

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.

Declaring and Initializing Strings

In C, there are several ways to initialize strings. Here’s a list of some common
methods:

1. Using Double Quotes (String Literal)


char str1[] = "Hello";

 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).

2. Using Character Array with Explicit Size


char str2[10] = "Hello";

 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.

3. Using Character Array with Individual Characters


char str3[] = {'H', 'e', 'l', 'l', 'o', '\0'};
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

 Each character, including the null terminator, is specified explicitly.


 This method is more verbose but gives full control over each character.

4. Without Null Terminator (Not Recommended)


char str4[] = {'H', 'e', 'l', 'l', 'o'};

 This creates an array of characters without a null terminator.


 Although it compiles, functions that expect a null-terminated string may
behave unpredictably. This is generally discouraged for string usage.

5. Initializing as a Pointer to a String Literal


char *str5 = "Hello";

 Here, str5 is a pointer to a string literal stored in read-only memory. It


points to the first character of "Hello".
 This method saves space but trying to modify str5 would lead to
undefined behavior, as string literals are often stored in read-only
memory.

6. Using strcpy to Initialize an Array


char str6[10];
strcpy(str6, "Hello");

 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:

str[strcspn(str, "\n")] = '\0'; // Remove newline character, if present

3. Using gets (Not Recommended)

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;
}

In C, puts is a standard library function used to print a string followed by a


newline character (\n). It is simpler than printf for printing strings because it
automatically appends the newline after the string, so you don’t have to include
\n manually.

Syntax
int puts(const char *str);

 str is the string you want to print.


K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

 puts returns a non-negative value on success and EOF on failure.

Example Usage of puts

#include <stdio.h>

int main() {
char greeting[] = "Hello, world!";
puts(greeting); // Prints "Hello, world!" followed by a newline

return 0;
}

Key Points About puts

1. Automatic Newline: puts adds a newline automatically after printing the


string, which is helpful when you just want to print a line of text and
move to the next line.
2. Simpler than printf for Strings: You don’t need to specify format
specifiers like % s. Just pass the string directly.
3. Returns an Integer: puts returns a non-negative integer if successful, or
EOF if an error occurs (although errors are rare).
4. Printing Literals: You can directly pass string literals to puts:

puts("Hello, C programming!");

Comparison with printf

 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:

printf("% s\n", greeting); // Equivalent to puts(greeting) with a newline

Example of puts and printf

#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

String Handling Functions in C

The <string.h> library provides several built-in functions for manipulating


strings. Let’s dive into each of these functions, their purpose, usage, and
examples.

1. strlen - Returns the Length of a String

strlen calculates the number of characters in a string until it encounters the


null character ('\0').

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:

Length of the string: 13

Explanation:

 strlen returns 13 because there are 13 characters before the null


character in "Hello, World!".

2. strcpy - Copies One String to Another

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];

strcpy(destination, source); // Copies source to destination


printf("Copied String: % s\n", destination);
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

return 0;
}

Output:

Copied String: Hello, C Programming!

Explanation:

 strcpy copies all characters from source to destination, so destination now


holds the same content as source .

. strcat - Concatenates Two Strings

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!";

strcat(str1, str2); // Concatenates str2 to the end of str1


printf("Concatenated String: % s\n", str1);

return 0;
}

Output:

Concatenated String: Hello, World!

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.

4. strcmp - Compares Two Strings

strcmp compares two strings lexicographically (dictionary order). It returns:

 0 if both strings are equal.


 A negative value if the first string is less than the second.
 A positive value if the first string is greater than the second.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";

int result1 = strcmp(str1, str2); // Compares str1 with str2


int result2 = strcmp(str1, str3); // Compares str1 with str3

printf("Comparison of str1 and str2: % d\n", result1);


printf("Comparison of str1 and str3: % d\n", result2);

return 0;
}

Output:

Comparison of str1 and str2: -1


Comparison of str1 and str3: 0

Explanation:

 result1 is -1 because "apple" is lexicographically less than "banana".


 result2 is 0 because "apple" and "apple" are identical.

. strchr - Searches for a Character in a String

strchr searches for the first occurrence of a character in a string. It returns a


pointer to the character if found, or NULL if the character isn’t found.

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:

Character 'o' found at position: 4

Explanation:

 strchr returns a pointer to the first occurrence of 'o' in "Hello, World!". The
position is 4 (0-based index).

6. strstr - Searches for a Substring within a String

strstr finds the first occurrence of a substring within a string. It returns a


pointer to the start of the substring if found, or NULL if the substring isn’t
found.

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:

Substring 'World' found at position: 7

Explanation:

 strstr returns a pointer to the beginning of the substring "World" in "Hello,


World!". The position is 7 (0-based index).

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

Implementation Of String Copy And String Concatenation


Without Using String Library Functions.

String Copy Program


#include <stdio.h>

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;

// Copying the string from source to destination


while (source[i] != '\0') { // Continue until the null terminator is reached
destination[i] = source[i]; // Copy character by character
i++;
}
destination[i] = '\0'; // Add the null terminator to the end of destination

printf("Copied String: % s\n", destination); // Print the copied string

return 0;
}

Explanation of String Copy Program

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

String Concatenation Program


#include <stdio.h>

int main() {
char destination[50] = "Hello, "; // Destination string initialized
char source[] = "world!"; // Source string to be concatenated
int i = 0, j = 0;

// Find the end of the destination string


while (destination[i] != '\0') { // Loop until the null terminator of destination
i++;
}

// Append the source string to the end of the destination string


while (source[j] != '\0') { // Loop through the source string
destination[i] = source[j]; // Append each character
i++;
j++;
}
destination[i] = '\0'; // Add null terminator to the end of the concatenated string

printf("Concatenated String: % s\n", destination); // Print the concatenated string

return 0;
}

Explanation of String Concatenation Program

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

7. Null Terminator: After appending all characters from source, a null


terminator is added to the end of the destination array to signify the end of
the concatenated string.
8. Output: The program uses printf to display the concatenated string.
9. Return Statement: The program returns 0, indicating successful
completion.

String Length Program


#include <stdio.h>

int main() {
char str[] = "Hello, world!"; // Input string
int length = 0; // Variable to hold the length

// Calculate the length of the string


while (str[length] != '\0') { // Continue until the null terminator is found
length++; // Increment length for each character
}

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

return 0;
}

Explanation of the String Length Program

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.

You might also like