Module 4
Strings and Pointers
13.1 to 13.6
13.1 Introduction
•A string is a sequence of characters.
•A string is a null-terminated character array.
•After the last character a null character(‘\0’) is stored to signify
end of character array.
•Ex: char str[]=“Hello”;
•How many locations we need to store?
•Subscripts are used to access elements of character array.
•Subscripts starts with a zero(0)
•Stored in successive memory locations
•ASCII characters are stored and not character itself 1.e H=72 ,
72 is stored
• General form of declaring a string:
– char str[size];
– Eg.: char mesg[100];
• Initialising Strings:
• Assigning value while declaring strings:
– char str[]=“HELLO”;
• Initialize string as array of characters:
• char str[]={‘H’ , ‘E’ , ‘L’ , ‘L’ , ‘O’, ‘\0’};
Declare a string with size much larger than no. of
elements initialised:
char str[10]=“HELLO”;
• char str[3];
str=“HELLO”;
generates compile time error- initialized with
more elements and initialization and
declaration cannot be separated
13.1.1 Reading Strings
• Ex: char str[100];
• str can be read using the following ways:
– scanf function
• scanf(“%s”,str);// no & operand ,
• Drawback of scanf() -blank space
– gets() function -takes the starting address of the string and
reads a a string or text line.
– getchar() - read a single character from the input
stream(stdin) and displays on the screen
– getch()- reads a single character at a time without waiting
for enter key to be pressed but never displays the output.
– getche()- reads character input from keyboard and echos
the input character on the output screen.
– Explicitly terminate with Null character
main()
{
int age;
char name[10];
printf(“Enter your age”);
scanf(“%d”,&age);
printf(“Enter your name”);
scanf(“%s”,age);
printf(“Age =%d, Name=%s”,age,name);
}
#include <stdio.h>
int main() {
char str[50];
// Using gets
printf("Enter a string using gets: ");
gets(str);
printf("String entered using gets: %s\n", str);
// Using getc
printf("Enter a character using getc: ");
char ch_getc = getc(stdin);
printf("Character entered using getc: %c\n", ch_getc);
// Using getch
printf("Enter a character using getch: ");
char ch_getch = getch();
printf("\nCharacter entered using getch: %c\n", ch_getch);
// Using getche
printf("Enter a character using getche: ");
char ch_getche = getche();
printf("\nCharacter entered using getche: %c\n", ch_getche);
// Using getchar
printf("Enter a character using getchar: ");
char ch_getchar = getchar();
printf("\nCharacter entered using getchar: %c\n", ch_getchar);
return 0;
}
13.1.2 Writing Strings
• Strings are displayed on screen using three
ways:
• printf() function
• printf(“%s”,str);
• printf(“%5.3s”,str);// right justified
• printf(“%-5.3s”,str);// left justified
puts() function// writes a line of output on screen
• puts(str);
putchar() function repeatedly// to print sequence of
characters
#include <stdio.h>
int main() {
// Using puts to print a string
puts("Hello, World!");
// Using putchar to print individual characters
putchar('C');
putchar(' ');
putchar('P');
putchar('r');
putchar('o');
putchar('g'); Output:
putchar('r'); Hello, World!
C Program
putchar('a');
putchar('m');
putchar('\n'); // Move to the next line
return 0;
}
String Taxonomy
Operations on Strings
• Finding Length of a string
• Converting characters of a string into upper case
• Converting characters of a string into lower case
• Concatenating two strings to form a new string
• Appending a string to another string
• Comparing two strings
• Reversing a string
• Extracting a substring from left, right and middle
• Inserting a string in another string
• Indexing
• Deleting
Finding Length of a string
Converting characters of a string into upper case
e= 101 to convert to E=69 minus 32
101- 32= 69->E
Converting characters of a string into lower case
A= 65 to convert to a= 97 add 32
65+32=97->a
Concatenating two strings to form a new string
Appending a string to another string
Source Destination
How are you? Hi
After Appending:
Hi How are you?
Comparing two strings
S1 and S2 are equal
S1 > S2
S1 < S2
Reversing a string
Extracting a substring from left
Hi there
No of characters to be copied: 2
Substring is : Hi
Extracting a substring from right
Hi there
No of characters to be copied: 5
Substring is : there
Extracting a substring from middle
Hi there
Enter the position from which to start the substring : 1
No of characters to be copied: 7
Substring is : i there
Inserting a string in another string
Enter main string: How you?
Enter string to be inserted: are
Enter position to insert: 5
New string is : How are you?
Indexing
Ex: INDEX(“Welcome to the world of programming“, "world”)=15;
//22-5+1=18
Deleting a string
EX:
DELETE(“ABCDXXXABCD”,4,3)= “ABCDABCD”
Replacing a pattern with another
Ex:
(“AAABBBCCC”, “BBB”, “X”) = AAAXCCC
(“AAABBBCCC”, “X” , “YYY”)= AAABBBCCC
CHARACATER
MANIPULATION
FUNCTIONS
13.5.2 String Manipulation Functions-
string.h & stdlib.h
• strcat, strncat
• strchr, strrchr
• strcmp, strncmp
• strcpy, strncpy
• strlen
• strstr
• strspn, strcspn
• strpbrk
• strtok,strtol,strtod
• atoi(),atof(),atol()
strcat Function
• Appends string pointed to by s2 to end of
string pointed to by s1.
• Syntax:
• char *strcat(char *str1, const char *str2);
• Example:
• s1[]=“C”;
• s2[]=“Programming”;
• Then, s1=C Programming;
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50]=“C”;
char s2[]=“Programming”;
strcat(str1, str2);
printf(“str1: %s”, str1);
}
strncat Function
• Appends string pointed to by s2 to end of string
pointed to by s1 up to n characters
• Syntax:
char *strncat(char *str1, const char *str2, size_t n);
• Example:
strncat(str1, str2,2);
• s1[]=“C”;
• s2[]=“Programming”;
Output:
C Pr
strchr Function
• Searches for first occurrence of character c in the
string str.
• Syntax:
• char *strchr(const char *str, int c);
• Example:
• str[10]=“Programming”
pos=strchr(str,’n’);
Output:
n=9
int main()
{
char str[50]=“ Programming in C”;
char *pos;
pos=strchr(str, ‘n’);
if( pos)
printf(“ n is found at position %d”,pos);
else
printf(“ n Is not found”);
}
strrchr Function
• Finds the last occurrence of a character in a string.
• Searches for first occurrence of character c beginning at
rear end and working towards front of string str.
• Syntax:
• char *strrchr(const char *str, int c);
• Example:
• //same as previous
• strrchr(str,’n’);
• Output:
• n=13
example
• #include <stdio.h>
• #include <string.h>
• int main() {
• char str[] = "Hello World";
• char *pos = strrchr(str, 'o');
• if (pos) {
• printf("Found at position: %ld\n", pos - str); // Output: 7
• }
• return 0;
• }
strcmp function
• Compares string pointed to by str1 to string
pointed to by str2.
• Function returns 0 if strings are equal, less
than zero if str1 is less than str2 and returns
greater than zero if str1 is greater than str2.
• Syntax:
• int strcmp(const char *str1, const char *str2);
strncmp
• Compares first n bytes of str1 and str2.
• Syntax:
• int strncmp(const char *str1, const char *str2,
size_t n);
strcpy
• Copies the string pointed to by str2 to str1
• Syntax:
• char *strcpy(char *str1, char *str2);
strncpy
• Copies up to n characters from s2 to s1
• Syntax:
• char *strncpy(char *str1,const char *str2,
size_t n);
strlen
•Finds length of string.
Syntax:
size_t strlen(const char *str);
strstr
•Find the first occurrence of string str2 in str1
Syntax:
char *strstr(const char *str1,const char *str2);
strspn
Function returns index of first character in str1 that doesn’t match any character
in str2
Syntax:
size_t strspn(const char*str1, const char*str2);
strcspn
Function returns index of first character in str1 that matches any character in str2
Syntax:
size_t strcspn(const char*str1, const char*str2);
strpbrk function
• Function returns a pointer to the first occurrence in str1 of any character
in str2 or NULL if none are present
• Syntax:
• char *strpbrk(const char*str1, const char*str2);
• Example:
• str1[]=“Programming in C”;
• str2[]=“AB”;
• No character matches in the two strings
strtok
• Isolate sequential tokens in a str by using delimiters
• char *strtok(char *str1,const char *delimiter);
• char str[]=“Hello, to, the, world, of, programming”;
• char delim[]=“ , “;
• Output:ex
Hello
to
the
world
of
programming
strtol
• Converts the string pointed by str to a long value
Converts a string to a long int, considering a specified base (e.g., decimal, hexadecimal).
• Syntax:
• long strtol(const char *str, char **end, int base);
• Example:
• num=strtol(“12345 Decimal value”, NULL, 10);
printf(“%ld”, num);
• num=strtol(“10110101 Binary value”, NULL, 2);
printf(“%ld”, num);
• Output:
12345
181
• #include <stdio.h>
• #include <stdlib.h>
• int main() {
• char str[] = "12345abc";
• char *end;
• long num = strtol(str, &end, 10); // Base 10
• printf("Number: %ld, Remaining string: %s\n", num, end);
• return 0;
• }
o/p
• Number: 12345, Remaining string: abc
strtol (String to Long Integer)
: Converts a string to a long int, considering a specified base (e.g., decimal, hexadecimal).
Use
Syntax: long int strtol(const char *str, char **endptr, int base);
•str: Input string.
•endptr: Pointer to the remaining part of the string after the number (can be NULL if not needed).
•base: Numeric base (e.g., 10 for decimal, 16 for hexadecimal).
strtod
• Function accepts a string str that has optional
+ or – sign followed by either:
• a decimal number( sequence of decimal digits
and a decimal point)
• a hexadecimal number(OX or ox with
hexadecimal digits and a decimal point)
• Syntax:
• double strtod(const char *str, char **end);
• Example:
• num=strtod(“123.345abcdefg”,NULL);
• Output:
123.345000
atoi()
• Converts a string to an int.
int i=1; // i=1
• int i=‘1’; //i=49,ASCII value of character 1
• atoi() converts a given string into integer
• use stdlib.h
• Syntax:
• int atoi(const char *str);
• Ex:
• i=atoi(“123.456”);
• RESULT: i=123
Converts a string to a double.
atof()
• Converts string to a double value and returns
the value to the function.
• Syntax:
• double atof(“12.39 is the answer”);
• RESULT: x: 12.39
• Converts a string to a double
atol()
• Converts string into a long int value.
• Syntax:
• long atol(const char *str);
• Ex:
• x=atol(“12345.6789”);
• RESULT: x: 12345L
13.6 Arrays of strings
• String of strings or array of strings
• Declaration:
• char names[20][30];// no of strings needed, length of
individual string
• i.e 20 names of max 30 characters
• Syntax for declaring 2D array:
• <data type> <array_name> [row_size][col_size];
• Ex:
• char name[5][10]={“Ram”, “Mohan”, “Sita”, “Hari”,
“Gopi”};
Programs on string
1.Program to find length of a string
#include <stdio.h>
int main()
{
char s[] = “HELLO";
int i;
for (i = 0; s[i] != '\0'; ++i)
printf("Length of the string: %d", i);
return 0;
}
OR
#include <stdio.h>
int main()
{
char text[100];
int i= 0;
printf("Enter any string: ");
gets(text);
while(text[i] != '\0')
{
i++;
}
printf("Length of '%s' = %d", text, i);
return 0;
}
2.Converting characters of a string into upper case
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
int i;
printf(“Enter a string : ");
gets(s);
for (i = 0; s[i]!='\0'; i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
{
s[i] = s[i] -32;
}
}
printf("String in Upper Case = %s", s);
return 0;