0% found this document useful (0 votes)
5 views

String

The document provides an overview of strings in C programming, explaining their definition, storage as ASCII values, and operations such as concatenation, comparison, and length calculation. It details string handling functions, input/output methods, and common string functions like strlen(), strcpy(), and strcat(). Additionally, it includes example programs demonstrating string manipulation and error identification in string operations.

Uploaded by

tanishkansara77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

String

The document provides an overview of strings in C programming, explaining their definition, storage as ASCII values, and operations such as concatenation, comparison, and length calculation. It details string handling functions, input/output methods, and common string functions like strlen(), strcpy(), and strcat(). Additionally, it includes example programs demonstrating string manipulation and error identification in string operations.

Uploaded by

tanishkansara77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Ch- String

1. Definitions and Concepts


What is a string?
A string is a sequence of characters. Strings are useful to store the non-numerical
quantities such as name, address etc. The C stores the characters as ASCII values in
memory. Hence. internally string is a sequence of ASCIIs. Each string in C is ended
with the special character called null character and denoted as '\O' or NULL. For
example string 'hello' is stored as

'h' 'e' 'l' 'l' 'o' '\0'

Here. first ASCII of h, then ASCII of e, ASCII of l, ASCII of l. ASCII of o and last the \0
(NULL) character are stored. Hence, string with five characters needs six bytes of
storage. Once a string is stored, many operations can be performed on it. For
example.
• Printing a string
• Computing length of string
• Concatenation of two strings
• Comparing two strings
• Finding small string into large string
• Converting uppercase string to lowercase
• Reversing a string

String handling in C

This section discusses the declaration, initialization, reading and printing of the
strings in detail. The string is declared as follows.
char s[10);
where s is a string which can store maximum 9 characters as one byte is needed to
store the ‘/0' character. The string can also be initialized at the time of declaration
as follows.
char city[7] = "Rajkot";
The same can also be done as
char city[7] ( ‘R’ , ‘a’ , ‘j’ , ‘k’ , ‘o’ , ‘t’ , ‘\0' };
In above, the size is not compulsory and if not given, compiler automatically
computes and puts it.
Reading a string :
There are two functions to read a string : scanf() and gets(). The major difference
between them is that scanf() reads only upto first blank or tab while gets() reads
upto newline. Hence. scanf() is useful to read only words while gets() can be used
Prof. Maulik Kakadiya
Programming in C
to read strings with blanks and tabs also. The statement
scanf ("%s",name);
when user enters the following input from the keyboard
Maulik Kakadiya
assigns only first word i.e. "Maulik" to string variable name. The second word
"Kakadiya” remains into the buffer and subsequent scanf() may read it. The
statement
scanf("%s %s",fname,lname);
when user enters earlier input assigns "Maulik" to string fname and "Kakadiya" to
string lname. If total input "Maulik Kakadiya" is to be assigned .to a single string
name, the following gets() is used.
gets (name);

Printing a string

The printf() is used to print the string with %s. For example,
printf("%s",city);
prints the string stored in the string variable city.

2. String I/O Functions

• gets(): Reads a string from standard input.


o Syntax: gets(str);
o Note: gets() is unsafe and can cause buffer overflow.
• puts(): Displays a string to the standard output.
o Syntax: puts(str);
• getchar() and putchar(): Read and write a single character.
o Syntax: char ch = getchar(); and putchar(ch);

3. Common String Functions

• strlen() - Returns the length of a string.


o Syntax: int len = strlen(str);
• strcpy() - Copies one string to another.
o Syntax: strcpy(destination, source);
• strncpy() - Copies specified number of characters.
o Syntax: strncpy(destination, source, n);
• strcat() - Appends one string to another.
o Syntax: strcat(str1, str2);
• strcmp() - Compares two strings.
o Syntax: int result = strcmp(str1, str2);
• strncmp() - Compares a specified number of characters.
o Syntax: int result = strncmp(str1, str2, n);
• strstr() - Finds the first occurrence of a substring.
o Syntax: char* result = strstr(str1, str2);
Prof. Maulik Kakadiya
Programming in C
4. Error Identification Examples

• Example 1:

char str[10];
strncpy(str, "god", 3);
printf("%s", str); // Error: No null character to terminate string

Solution: Use strncpy(str, "god", 4); to ensure null character.

• Example 2:

char str[10];
strcpy(str, "balagurusamy"); // Error: Overflow, array size
insufficient

Solution: Increase array size: char str[20];

5. Functions for Writing Strings to Screen

1. Using puts()

o Directly prints a string to the standard output.


o Automatically appends a newline (\n) at the end.

#include <stdio.h>
int main() {
char str[] = "Hello, World!";
puts(str);
return 0;
}

2. Using printf()

o Provides formatted output using placeholders.

#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("Output using printf: %s\n", str);
return 0;
}

• 3. Using putchar()
o Prints a single character to the screen.

#include <stdio.h>
int main() {
char str[] = "Hello";
for(int i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
putchar('\n');
Prof. Maulik Kakadiya
Programming in C
return 0;
}

4. Using fputs()

o Writes a string to the specified output stream (e.g., stdout).

#include <stdio.h>
int main() {
char str[] = "Hello, World!";
fputs(str, stdout);
putchar('\n');
return 0;
}

Programs
1. Program to Compare Two Strings and Display Result
#include <stdio.h>
#include <string.h>

int main() {
char str1[50], str2[50];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

if (strcmp(str1, str2) == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");

return 0;
}
Output: Enter first string: Hello
Enter second string: Hello
Strings are equal.

2. Program to Find Length of String using strlen()


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

int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length of string: %lu\n", strlen(str));
return 0;
}
Input and Output:
Prof. Maulik Kakadiya
Programming in C
Enter a string: “hello world”
Length of string: 11
Explanation:
The string "hello world" consists of 11 characters:

h, e, l, l, o, (space), w, o, r, l, d

The strlen() function returns the number of characters excluding the null character \0.

Hence, the length is 11.

3. Program to Demonstrate strcat(), strcmp(), and strncpy()


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

int main() {
char str1[50] = "Hello";
char str2[50] = " World";
char str3[50];

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

// strcmp
if (strcmp(str1, str2) == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");

// strncpy
strncpy(str3, str1, 5);
str3[5] = '\0';
printf("Copied String using strncpy: %s\n", str3);

return 0;
}
Initial Values:
• str1 = "Hello"
• str2 = " World"
• str3 is an empty character array.

Step 1: Concatenation using strcat()


strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
• strcat() appends str2 to the end of str1.
• str1 becomes "Hello World".
Output:
Concatenated String: Hello World

Step 2: Comparison using strcmp()


if (strcmp(str1, str2) == 0)

Prof. Maulik Kakadiya


Programming in C
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");
• strcmp() compares "Hello World" with " World".
• They are not equal.
Output:
Strings are not equal.

Step 3: Copy using strncpy()


strncpy(str3, str1, 5);
str3[5] = '\0'; // Manually adding null terminator
printf("Copied String using strncpy: %s\n", str3);
• strncpy() copies 5 characters from "Hello World" to str3.
• The copied string in str3 will be "Hello".
• The null terminator ('\0') is added to mark the end of the string.
Output:
Copied String using strncpy: Hello

Final Output
Concatenated String: Hello World
Strings are not equal.
Copied String using strncpy: Hello

4. Program to Read String using getchar() and Display using putchar()


#include <stdio.h>

int main() {
char ch;
printf("Enter a string (Press Enter to stop): ");
while ((ch = getchar()) != '\n') {
putchar(ch);
}
return 0;
}

Example Input and Output:

Input:

Hello World

Output:

Hello World

Explanation:

• The program reads each character using getchar().

Prof. Maulik Kakadiya


Programming in C
• It immediately prints the character using putchar().
• When the Enter key ('\n') is pressed, the loop stops, and the program terminates.

5. Program to Read and Display ASCII Values of Each Character


#include <stdio.h>

int main() {
char str[50];
printf("Enter your name: ");
gets(str);

printf("ASCII values of your name: \n");


for (int i = 0; str[i] != '\0'; i++) {
printf("%c: %d\n", str[i], str[i]);
}
return 0;
}

The output of the given program will depend on the name entered by the user. The program
works as follows:

1. It prompts the user to enter their name using gets().


2. It prints each character of the name along with its corresponding ASCII value using
printf.
3. The loop continues until it reaches the null character (\0), which marks the end of
the string.

Example 1

Input:

Enter your name: John

Output:

ASCII values of your name:


J: 74
o: 111
h: 104
n: 110

Example 2

Input:

Enter your name: Alice


Prof. Maulik Kakadiya
Programming in C
Output:

ASCII values of your name:


A: 65
l: 108
i: 105
c: 99
e: 101

Explanation:

• Each character has a unique ASCII (American Standard Code for Information
Interchange) value.
• The program uses str[i] != '\0' to check for the null terminator and prints each
character along with its ASCII value using:

printf("%c: %d\n", str[i], str[i]);

• ASCII values for uppercase letters (A-Z) range from 65 to 90 and lowercase letters
(a-z) range from 97 to 122.

6. Program to Read a String and Join it with Another String


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

int main() {
char str1[50], str2[50];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

strcat(str1, str2);
printf("Joined String: %s\n", str1);

return 0;
}

The program performs the following steps:


1. It takes two strings as input using gets().
2. It concatenates (joins) the second string to the end of the first string using the strcat()
function.
3. It prints the concatenated result.
Example 1
Input:
Enter first string: Hello
Enter second string: World
Output:

Prof. Maulik Kakadiya


Programming in C
Joined String: HelloWorld
Explanation: strcat() appends "World" to "Hello" without adding any extra space.

Example 2
Input:
Enter first string: Good
Enter second string: Morning
Output:
Joined String: GoodMorning

Prof. Maulik Kakadiya


Programming in C

You might also like