STRING
A string is a series of characters treated as a single unit.
•A string may include letters, digits and various special characters such
as +, -, *, / and $.
•In C language strings are stored in array of char type along with null
terminating character ‘\0’ at the end.
•String literals or string constants in C are written in double quotation
marks as follows:
“1000 Main Street”
Syntax :-
char string_name[size];
Reading strings:
Strings can be read from the user by using three ways;
1. Using scanf() function
2. Using gets() function
3. Using getchar(), getch(), or getche() function
repeatedly
Using scanf() function
A string can be read using scanf() by writing scanf(“%s”,
variable_name);
Although the syntax of scanf() function is well known and easy to use,
the main pitfall with this function is that it terminates as soon as it f inds
a blank space.
Example:
……..
char str[10];
printf(“Enter a string\n”);
scanf(“%s”,str);
………….
Using gets() function
The string can be read by writing
gets(str);
gets() is a function that overcomes the drawbacks of
scanf(). The gets() function takes the starting address of
the string which will hold the input. The string inputted using
gets() is automatically terminated with a null character.
Example:
…………..
char str[10];
printf(“Enter a string\n”);
gets(str);
…………..
Using getchar(), getch(), or getche() function
repeatedly
The string c an also be re ad by c alling the ge tc har()
repeatedly to read a sequence of single characters (unless
a terminating character is encountered) and simultaneously
storing it in a character array as follows:
Writing string
The string can be displayed on screen using three
ways:
1. Using printf() function
2. Using puts() function
3. Using putchar() function repeatedly
•The string can be displayed using pintf() by writing printf(“%s
”,str)
•The next method of writing a string is by using the puts()
function.
• The string can be displayed by writing:
puts(str);
•It terminates the line with a newline character (‘\n’).
Finally the string can be written by calling the putchar( )
function repeatedly to print a sequence of single
characters.
int i=0;
char str[10];
while(str[i]!=’\0’)
{
putchar(str[i]);
i++;
}
Example: Read and display a string
#include<stdio.h>
#include<conio.h>
main()
{
char str[20];
printf(“\n Enter a string:\n”);
gets(str); / scanf(“%s”, str);
printf(“The string is:\n”);
puts(str); / printf(“%s/n”,str);
getch();
}
#include <stdio.h>
#include <string.h>
int main()
{
// Declare an array of strings
// The first dimension (3) specifies the
number of strings.
// The second dimension (20) specifies
the maximum length of each string
(including the null terminator).
char names[3][20];
// Initialize the strings in the array using
strcpy
// Note: Direct assignment like names[0]
= "Alice"; is not allowed for character arrays
after declaration.
// Use strcpy to copy string literals into the
allocated memory.
strcpy(names[0], "Alice");
strcpy(names[1], "Bob");
strcpy(names[2], "Charlie");
// Print each string in the array
printf("List of names:\n");
for (int i = 0; i < 3; i++) {
printf("Name %d: %s\n", i + 1, names[i]);
}
return 0; // Indicate successful execution
}
Output:
List of names:
Name 1: Alice
Name 2: Bob
Name 3: Charlie
Write a C program to input a word from keyboard and how each character
followed by a new line
Sample Input: Bangladesh
Sample Output:
B
a
n
g
l
a
d
e
s
h
Write a program using for loop to print the following output
|C |
#include<stdio.h> |CP |
|CPr |
|CPro |
main() |CProg |
{ |CProgr |
int c, d; |CProgra |
|CProgram |
char string[] = "CProgramming"; |CProgramm |
printf("\n\n"); |CProgrammi |
|CProgrammin |
for( c = 0 ; c <= 11 ; c++ )
|CProgramming|
{ |CProgramming|
d = c + 1; |CProgrammin |
|CProgrammi |
printf("|%-12.*s|\n", d, string);
|CProgramm |
} |CProgram |
for( c = 11 ; c >= 0 ; c-- ) |CProgra |
|CProgr |
{ |CProg |
d = c + 1; |CPro |
|CPr |
printf("|%-12.*s|\n", d, string);
|CP |
} |C |
}
C|
#include<stdio.h> | CP|
| CPr|
| CPro|
main()
| CProg|
{ | CProgr|
int c, d; | CProgra|
| CProgram|
char string[] = "CProgramming";
| CProgramm|
printf("\n\n"); | CProgrammi|
for( c = 0 ; c <= 11 ; c++ ) | CProgrammin|
|CProgramming|
{ |CProgramming|
d = c + 1; | CProgrammin|
| CProgrammi|
printf("|%12.*s|\n", d, string);
| CProgramm|
} | CProgram|
for( c = 11 ; c >= 0 ; c-- ) | CProgra|
| CProgr|
{
| CProg|
d = c + 1; | CPro|
printf("|%12.*s|\n", d, string); | CPr|
| CP|
} | C|
}
Character strings are often used to build meaningful
and readable programs. The common operations
performed on character strings include:
1. Combining strings together.
2. Copying one string to another.
3. Comparing strings for equality.
4. Extracting a portion of a string.
String-Handling Functions
Copy String
In C programming, "copy string" refers to the process of duplicating the
contents of one string (a sequence of characters terminated by a null
character) into another string. This is typically achieved using library
functions provided in the <string.h> header file.
The primary function for string copying in C is strcpy().
#include <stdio.h>
#include <string.h>
int main()
{
char source_string[] = "Hello, C!";
char destination_string[20];
strcpy(destination_string, source_string);
printf("Source: %s\n", source_string);
printf("Destination: %s\n",
destination_string);
return 0;
}
Source: Hello, C!
Destination: Hello, C!
Append String
In C programming, "append string" refers to the process of
adding one string to the end of another string.
The strcat() function (from the string.h library) is used to
concatenate two strings. It takes two arguments: the
destination string and the source string. The source string
is appended to the end of the destination string.
#include <stdio.h>
#include <string.h>
int main()
{
char dest[50] = "Hello";
char src[] = " World!";
strcat(dest, src);
printf("%s\n", dest);
return 0;
}
Output: Hello World!
Compare two String
In C, comparing two strings typically involves determining
if they are identical or, if not, which one comes f ir st
lexicographically (alphabetically). The standard library
function strcmp() is the primary tool for this purpose.
Compare two String
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
char str3[] = "world";
// Compare str1 and str2
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal.\n");
} else {
printf("str1 and str2 are not equal.\n");
}
// Compare str1 and str3
int result = strcmp(str1, str3);
if (result == 0) {
printf("str1 and str3 are equal.\n");
} else if (result < 0) {
printf("str1 is less than str3.\n");
} else {
printf("str1 is greater than str3.\n");
}
return 0; str1 and str2 are equal.
} str1 is less than str3.
Return String Length
#include <stdio.h>
#include <string.h>
int main() {
char myString[] = "Hello";
size_t length = strlen(myString); // size_t
is an unsigned integer type
printf("The length of the string \"%s\" is:
%zu\n", myString, length);
return 0;
}
The length of the string "Hello" is:
5
Find a character in string
#include <stdio.h>
#include <string.h>
int main() {
char myString[] = "Hello, world!";
char searchChar = 'w';
char *result;
result = strchr(myString, searchChar);
if (result != NULL) {
printf("Character '%c' found at position: %ld\n",
searchChar, result - myString);
} else {
printf("Character '%c' not found in the string.\n",
searchChar, result - myString);
}
return 0;
}
Character 'w' found at position: 7
Find string S2 in S1
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "This is a test string.";
char s2[] = "test";
char s3[] = "example";
char *result1 = strstr(s1, s2);
char *result2 = strstr(s1, s3);
if (result1 != NULL) {
printf("'%s' found in '%s' at position: %ld\n", s2, s1, result1 - s1);
} else {
printf("'%s' not found in '%s'\n", s2, s1);
}
if (result2 != NULL) {
printf("'%s' found in '%s' at position: %ld\n", s3, s1, result2 - s1);
} else {
printf("'%s' not found in '%s'\n", s3, s1);
}
return 0;
}
'test' found in 'This is a test string.' at position: 10
'example' not found in 'This is a test string.'
Program
Example: Consider s1, s2 and s3 are three string variables.
Write a program to read two string constants into s1 and s2
and compare whether they are equal or not. If they are not,
join them together. Then copy the contents of s1 to the
variable s3. At the end the program should print the contents
of all three variables and their length.
#include<stdio.h>
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int x,a1,a2,a3;
printf("\n Enter two string constants\n");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("\n Strings are not equal\n");
strcat(s1,s2);
}
else
printf("\n Strings are equal\n");
strcpy(s3,s1);
a1=strlen(s1);
a2=strlen(s2);
a3=strlen(s3);
printf("\n length of strings :\n s1_ %s= %d\n s2_ %s= %d\n
s3_ %s= %d",s1,a1,s2,a2,s3,a3);
}