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

Strings

Uploaded by

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

Strings

Uploaded by

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

Strings:

 Introduction
o A String in C programming is a sequence of characters terminated with a null character ‘\0’.
o The C String is stored as an array of characters.
o The difference between a character array and a C string is that the string in C is terminated with a unique character ‘\0’.
o

C String Declaration Syntax


o Declaring a string in C is as simple as declaring a one-dimensional array.
 Below is the basic syntax for declaring a string.
 char string_name[size];
o In the above syntax string_name is any name given to the string variable and size is used to define the length of the string, i.e the
number of characters strings will store.
o There is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of a string that differs
strings from normal character arrays.
C String Initialization

A string in C can be initialized in different ways”.

1. Assigning a String Literal without Size


String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array.
char str[] = "GeeksforGeeks";

2. Assigning a String Literal with a Predefined Size


String literals can be assigned with a predefined size. But we should always account for one extra space which will be assigned to the null
character. If we want to store a string of size n then we should always declare a string with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning Character by Character with Size
We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning Character by Character without Size
We can assign character by character without size with the NULL character at the end. The size of the string is determined by the compiler
automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

STRING HANDLING FUNCTIONS/ operations on strings,

o C library supports a large number of string handling functions.


o These functions are stored under the header file string.h in the program.
strlen Strcat
o strlen() function strlen() is used to return the length of the  It is used to concatenate two strings
string , that means counts the number of characters  The second string will be appended to the end of first string.
present in a string.  Syntax: strcat (string variable1, string variable2);
o Syntax integer variable = strlen (string variable);
Strcmp() function Strcpy()
 The strcmp function compares two strings.  It is used to copy one string to another
 The strings are compared character by character, until there is a  It copies the contents of second string to first string.
mismatch or end of one of the string is reached.(whichever is  Syntax: strcpy(string variable1, string variable2);
earlier)
 The function returns
0 (Zero) if the strings are equal
Value< if str1 is less than str2
0(Zero)
Value> if str1 is greater than str2
0(Zero)
 Syntax: strcmp(string variable1, string variable2);
Strrev()
 It is used to reverse the characters in a given string
 Syntax: strrev(string variable);

STRING TAXONOMY
 In C, we can store a string either in fixed-length format or in variable-length format as shown
Fixed-length string
o When storing a string in a fixed- length format, specify an appropriate size for the string variable.
o If the size is too small, then it will not be able to store all the elements in the string.
o On the other hand, if the string size is large, then unnecessarily memory space will be wasted.
Variable-length string
o The string can be expanded or contracted to accommodate the elements in it.
o For example, if a string variable is declared to store the name of a student. If a student has a long name of say 20 characters, then the
string can be expanded to accommodate 20 characters.
o On the other hand, a student name has only 5 characters, then the string variable can be contracted to store only 5 characters.
o However, to use a variable-length string format a technique is needed to indicate the end of elements that are a part of the string.
o This can be done either by using length-controlled string or a delimiter.

Length-controlled string
o In a length-controlled string, specify the number of characters in the string.
o This count is used by string manipulation functions to determine the actual length of the string variable.
Delimited string
o In this format, the string is ended with a delimiter.
o The delimiter is then used to identify the end of the string.
o For example, in English language every sentence is ended with a full-stop (.).
o In C any character such as comma, semicolon, colon, dash, null character, etc. are used as the delimiter of a string.
o Null character is the most commonly used string delimiter in the C language.

MISCELLANEOUS STRING AND CHARACTER FUNCTIONS


In this section, we will discuss some character and string manipulation functions that are part of ctype.h, string.h, and stdlib.h.

Character Manipulation Functions


String Manipulation Functions
commonly used string functions present in the string.h header file.
strcat Function strncat Function
Syntax: Syntax:
char *strcat (char *strl, const char *str2); char *strncat (char *strl, const char *str2, size_t n);
 The strcat function appends the string pointed to by  This function appends the string pointed to by str2 to the
str2 to the end of the string pointed to by strl.
end of the string pointed to by str1 up to n characters long.
 The terminating null character of strl is overwritten.
 The process stops when the terminating null  The terminating null character of strl is overwritten.
character of str2 is copied.  Copying stops when n characters are copied or the
 The argument strl is returned. Note that strl should terminating null character of str2 is copied.
be big enough to store the contents of str2.
 A terminating null character is appended to str1 before

#include <stdio.h> returning to the calling function.


#include <string.h> #include <stdio.h>
int main() #include <string.h>
} int main()
char str1 [50] = "Programming"; {
char str2 [ ] = "In C"; char str1 [50] = "Programming";
strcat (str1, str2); char str2 [] = "In C";
printf("\n str1: %s", str1); strncat (strl, str2, 2);
return 0; printf("\n str1: %s", str1);
} return 0;
Output }
Str1: Programming In C Output
strl: Programming In
strchr Function strrchr Function
Syntax: Syntax:
char *strchr(const char *str, int c); char *strrchr (const char *str, int c);
 The strchr() function searches for the first  The strrchr() function searches for the first occurrence of
occurrence of the character c (an unsigned char) in the character c (an unsigned char) beginning at the rear end
the string pointed to by the argument str. and working towards the front in the string pointed by str.
 The function returns a pointer pointing to the first  The function searches for the last occurrence of the
matching character, or null if no match is found. character c and returns a pointer pointing to the last
#include <stdio.h> matching character, or null if no match is found.
#include <string.h> #include <stdio.h>
int main() #include <string.h>
{ int main()
char str[50] = "Programming In C"; {
char *pos; char str[50] = "Programming In C";
pos = strchr(str, 'n'); char *pos;
if (pos) pos = strrchr(str, 'n');
printf("\n n is found in str at position %d", pos); if (pos)
else printf("\n The last position of n is: %d", pos-str);
printf("\n n is not present in the string"); else
return 0; printf("\n n is not present in the string");
} return 0;
Output }
n is found in str at position 9 Output
The last position of n is: 13
strcmp Function strncmp Function
int strcmp (const char *strl, const char *str2); Syntax:
 The strcmp function compares the string pointed to int strncmp (const char *strl, const char *str2, size_t n);
by str1 to the string pointed to by str2.  This function compares at most the first n bytes of strl and str2
 The function returns and stops comparing after the null character is encountered.
 zero if the strings are equal.  The function returns
 returns a value less than zero if str1 is less than  zero if first n bytes of the strings are equal.
str2  returns a value less than zero if str1 is less than str2
 returns a value greater than zero if str1 is  returns a value greater than zero if str1 is greater than str2
greater than str2 #include <stdio.h>
#include <stdio.h> #include <string.h>
#include <string.h> int main()
int main() {
{ char str1 [10] = "HELLO";
char str1 [10] = "HELLO"; char str2 [10] = "HEY";
char str2 [10] = "HEY"; if (strncmp (strl, str2,2)==0)
if (strcmp(str1, str2)==0) printf("\n The two strings are identical");
printf("\n The two strings are identical"); else
else printf("\n The two strings are not identical");
printf("\n The two strings are not identical"); return 0;
return 0; }
} Output
Output The two strings are identical
The two strings are not identical
strcpy Function strncpy Function
Syntax: Syntax:
char *strcpy (char *st rl, const char *str2); char *strncpy (char *str1, const char *str2, size t n);
 This function copies the string pointed to by str2  It copies up to n characters from the string to str1 pointed
str1 including the null character of str2. to by str2 to str1 and stops when n characters are copied.
 It returns the argument strl.  if the null character in str2 is reached then the null
 Here str1 should be big enough to store the contents character is continually copied to str1 until n characters
of str2. have been copied.
#include <stdio.h>  Finally, a null character must be appended to str1.
#include <string.h>  However, if n is zero or negative then nothing is copied.
int main() #include <stdio.h>
{ #include <string.h>
char str1 [10], str2 [10] = "HELLO"; int main()
strcpy(strl, str2); {
printf("\n strl: %s", strl); char str1 [10], str2 [10] = "HELLO";
return 0; strncpy (strl, str2, 2);
} printf("\n str1: %s", str1);
Output return 0;
HELLO }
Output
HE

strlen Function strstr Function


Syntax: Syntax:
Size_t strlen (const char *str); char *strstr(const char *strl, const char *str2);
 This function calculates the length of the  This function is used to find the first occurrence of
string str up to but not including the null character. string str2 in the string str1.
 The function returns the number of characters in the  It returns a pointer to the first occurrence of str2 in strl.
string.  If no match is found, then a null pointer is returned.
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
int main() int main()
{ {
char str[] = "HELLO"; char strl [] = "HAPPY BIRTHDAY TO YOU";
printf("\n Length of str is: %d", strlen(str)); char str2 [] = "DAY";
return 0; char *ptr;
} ptr = strstr(str1, str2);
Output if (ptr)
Length of str is: 5 printf("\n Substring Found");
else
printf("\n Substring Not Found");
return 0;
}
Output
Substring Found

strspn Function strcspn Function


Syntax: Syntax:
size_t strspn (const char *str1, const char *str2); size_t strcspn (const char *strl, const char *str2);
 The function returns the index of the first character  The function returns the index of the first character in strl
in str1 that doesn't match any character in str2. that matches any of the characters in str2.
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
int main() int main()
{ {
char str1 [] = "HAPPY BIRTHDAY TO YOU"; char str1 [] = "PROGRAMMING IN C";
char str2 [] = "HAPPY BIRTHDAY JOE"; char str2 [] = "IN";
printf("\n The position of first character in str2 that does printf("\n The position of first character in str2 that matches with
not match with that in str1 is %d", strspn (strl, str2)); that in str1 is %d", strcspn (strl, str2));
return 0; return 0;
} }
Output Output
The position of first character in str2 that does not match The position of first character in str2 that matches with that in str1
with that in str1 is 15 is
strpbrk Function strtok Function
Syntax: Syntax:
char *strpbrk (const char *str1, const char *str2); char *strtok ( char *strl, const char *delimiter );
 It returns a pointer to the first occurrence in str1 of any  It is used to isolate sequential tokens in a null-terminated string, str and
character in str2, or NULL if none are present. are separated in the string using delimiters.
 The only difference between strpbrk() and strcspn is, strcspn  On first call, str should be specified; subsequent calls, wishing to
() returns the index of the character and strpbrk () returns a obtain further tokens from the same string, should pass a NULL
pointer to the first occurrence of a character in str2. pointer instead.
#include <stdio.h>  Delimiter must be supplied each time, between calls.
#include <string.h>  It returns a pointer to the beginning of each subsequent token in the
int main( ) string, after replacing the token itself with a NULL character. When all
{ tokens are left, a null pointer is returned.
char str1 [] = "PROGRAMMING IN C"; #include <stdio.h>
char str2 [] = "AB"; #include <string.h>
char *ptr = strpbrk (strl, str2); main ()
int main() {
if (ptr = = NULL) char str[] = "Hello, to, the, world of, programming";
printf("\n No character matches in the two strings"); char delim [] ", ", result [20]; Output
else result = strtok (str, delim); Hello
printf("\n Character in str2 matches with that in str1"); while (result!= NULL) to
return 0; { printf("\n %s", result); the
} Output: No character matches in the two strings result = strtok (NULL, delim); } world of
getch(); return 0; } programming
strtol Function strtod Function
Syntax: Syntax:
long strtol (const char *str, char **end, int base); double strtod (const char *str, char **end);
 The strtol function converts the string pointed  The function accepts a string str that has an optional plus
by str to a long value. ('+') or minus sign (-) followed by either:
 It skips leading white space characters and stops  a decimal number containing a sequence of decimal digits
when it encounters the first non- numeric optionally consisting of a decimal point, or
character.  a hexadecimal number consisting of a "0x" or "0x"
 strtol stores the address of the first invalid character followed by a sequence of hexadecimal digits optionally
in str in *end. containing a decimal point.
 If there were no digits at all, then the strtol function  In both cases, the number may be optionally followed by
will store the original value of str in *end. an exponent ('E' or 'e' for decimal constants or a 'p' or 'p' for
 NULL may be passed instead of *end if there is no hexadecimal constants), followed by an optional plus or
need to store the invalid characters anywhere. minus sign, followed by a sequence of decimal digits.
 Finally, the third argument base specifies whether  For decimal constants and hexadecimal constants, the
the number is in hexa-decimal, octal, binary, exponent indicates the power of 10 and 2, respectively, by
or decimal representation. which the number should be scaled.
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
main () main ()
{ {
long num; double num;
num = strtol ("12345 Decimal Value", NULL, 10); num = strtod ("123.345abcdefg", NULL);
printf("%ld", num); printf("%lf", num);
num = strtol ("65432 Octal Value", NULL, 8); getch();
printf("%ld", num); return 0;
strtol ("10110101 Binary Value", NULL, 2); }
printf("%ld", num); Output
num = strtol ("A7CB4 Hexadecimal Value",NULL, 16); 123.345000
printf("%ld", num);
getch();
return 0;
}
Output
12345
27418
181
687284

atoi () Function atof() Function


 The value 1 is an integer and '1' is a character.  The function atof () converts the string that it accepts as an
 A huge difference is when we write the two argument into a double value and then return that value to
statements given below the calling function.
int i=1; // here i =1  However, the string must start with a valid number.
int i='1'; // here i =49, the ASCII value of character 1  One point to remember is that the string can be terminated
 123 is an integer number but '123' is a string of with any non-numerical character, other than "E" or "e".
digits.  The syntax of atof () can be given as,
 C provides a function atoi that converts a given double atof ( const char *str);
string into its corresponding integer. Example
 The atoi() function converts a given string passed to X = atof("12.39 is the answer" );
it as an argument into an integer. RESULT: x = 12.39
 The atoi() function returns that integer to the calling
function. The string should start with a number.
 The atoi() will stop reading from the string as soon
as it encounters a non-numerical character.
 The atoi() is included in the stdlib.h file.
 The syntax of atoi() can be given as, atol() Functions
int atoi( const char *str);  The function atol () converts the string into a long int
Example value.
i = atoi( "123.456" );  The atol function returns the converted long value to the
RESULT: i = 123 calling function.
 Like atoi, the atol () will read from a string until it finds
any character that should not be in a long.
 Its syntax can be given as,
long atol ( const char *str);
Example
X = atol ( "12345.6789" );
RESULT: x = 12345L.

ARRAYS OF STRINGS
 An array of string is declared as,
char names [20] [30];
 The first index will specify how many strings are needed and the second index specifies the length of every individual string.
 It allocates space for 20 names where each name can be a maximum of 30 characters long.
 The general syntax for declaring a two-dimensional array of strings can be given
<data type> <array_name> [row_size] [column_ size];

Example:
 The memory representation of an array of strings.
 If we have an array declared as
char name [5] [10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};

Then in memory the array is stored as shown in Figure

 By declaring the array names, we allocate 50 bytes. But the actual memory occupied is 27 bytes. Thus we see, more than half of the
memory allocated lies wasted.
 Figure 6.21 shows an algorithm to process an individual string from an array of strings.

 In Step 1, we initialize the index variable I to zero.


 In Step 2, a while loop is executed until all the strings in the array are accessed.
 In Step 3, each individual string is processed.
Write a program to read and print the names of n students of a class.
#include <stdio.h>
#include <conio.h>
int main()
{
char names [5] [10];
int i, n;
clrscr();
printf("\n Enter the number of students: ");
scanf("%d", &n);
for (i=0;i<n;i++)
{
printf("\n Enter the name of student %d: ", i+1);
gets (names [i]);
}
printf("\n Names of the students are:\n");
for (i=0; i < n; i++)
puts (names[i]);
getch();
return 0;
}
Output
Enter the number of students: 3
Enter the name of student 1: Aditya
Enter the name of student 2: Goransh
Enter the name of student 3: Sarthak
Names of the students are: Aditya Goransh Sarthak

Write a program to sort names of students.


#include <stdio.h>
#include <conio.h>
int main()
{
char names [5] [10], temp [10];
int i, n, j;
clrscr();
printf("\n Enter the number of students: ");
scanf("%d", &n);
for (i=0;i<n;i++)
{
printf("\n Enter the name of the student %d: ", i+1);
gets (names [i]);
}
for (i=0;i<n;i++)
{
for(j=0;j< n-i-1;j++)
{
if (strcmp (names [j], names [j+1]) >0)
{
strcpy(temp, names [j]);
strcpy (names [j], names [j+1]);
strcpy (names [j+1], temp);
}
}
}
printf("\n Names of the students are: ");
for (i=0;i<n;i++)
puts (names [i]);
getch();
return 0;
}
Output
Enter the number of students: 3
Enter the name of student 1: Sarthak
Enter the name of student 2: Goransh
Enter the name of student 3: Aditya
Names of the students are: Aditya Goransh Sarthak

Write a program to read and print the text until a * is encountered. Also count the number of characters in the text entered.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[100];
int i=0;
clrscr();
printf("\n Enter * to end");
printf("\n Enter the text: ");
scanf("%c", &str[i]);
while (str[i] != ‘*’)
{
i++;
scanf("%c", &str[i]);
}
str[i] = '\0';
printf("\n The text is: ");
i=0;
while (str[i] != '\0')
{
printf("%c", str[i]);
i++;
}
printf("\n The count of characters is: %d", i);
return 0;
}
Output
Enter * to end
Enter the text: Hi there*
The text is: Hi there
The count of characters is: 8
Write a program to read a sentence. Then count the number of words in the sentence.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[200];
int i=0, count=0;
clrscr();
printf("\n Enter the sentence: ");
gets (str);
while (str[i] != '\0')
{
if (str[i] == && str[i+1] != ` ')
count++;
i++;
}
printf("\n The total count of words is: %d", count+1);
return 0;
}
Output
Enter the sentence: How are you
The total count of words is: 3

Write a program to read multiple lines of text until a* is entered. Then count the number of characters,words, and lines in the text.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[200];
int i=0, word_count = 0, line_count =0, char_count = 0;
clrscr();
printf("\n Enter a * to end");
printf("\n Enter the text: ");
scanf("%c", &str[i]);
while (str[i] != '*')
{
i++;
scanf("%c", &str[i]);
}
str[i] = '\0';
i=0;
while (str[i] != '\0')
{
if (str[i] =='\n' || i==79)
line_count++;
if (str[i] = '' && str[i+1] !=` ')
word_count++;
char_count++;
i++;
}
printf("\n The total count of words is: %d", word_count+1);
printf("\n The total count of lines is: %d", line_count+1);
printf("\n The total count of characters is: %d", char_count);
return 0;
}
Output
Enter the text: Hi there*
The total count of words is: 2
The total count of lines is: 1
The total count of characters is: 8

You might also like