0% found this document useful (0 votes)
3 views32 pages

Understanding C Strings and Functions

The document provides an overview of strings in C, defining them as one-dimensional arrays of characters terminated by a null character. It explains string declaration methods, differences between character arrays and string literals, and various string functions such as strlen, strcpy, strcat, and strcmp. Additionally, it discusses input methods for strings, including the use of gets() and fgets(), along with their advantages and drawbacks.

Uploaded by

mohdaffan0511
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

Understanding C Strings and Functions

The document provides an overview of strings in C, defining them as one-dimensional arrays of characters terminated by a null character. It explains string declaration methods, differences between character arrays and string literals, and various string functions such as strlen, strcpy, strcat, and strcmp. Additionally, it discusses input methods for strings, including the use of gets() and fgets(), along with their advantages and drawbacks.

Uploaded by

mohdaffan0511
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

String

 The string can be defined as the one-dimensional array of


characters terminated by a null ('\0’).
 The character array or the string is used to manipulate text such as
word or sentences
 Each character in the array occupies one byte of memory.
 The termination character ('\0') is important in a string since it is the
only way to identify where the string ends.
 When we define a string as char s[10], the character s[10] is
implicitly initialized with the null in the memory.

1.
12/14/2025
String Declaration
 There are two ways to declare a string in c language such as By
char array and By string literal
1. Declaring String by char Array
 char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0’};
 As we know, array index starts from 0, so it will be represented as
in the figure given below.

2. Declaring String by Literal


 char ch[]="javatpoint";
 In such case, '\0' will be appended at the end of the string by the
compiler.

2.
12/14/2025
Difference between char Array and string Literal
 We need to add the null character '\0' at the end of the array by
ourself whereas, it is appended internally by the compiler in the
case of the character array.
 The string literal cannot be reassigned to another set of characters
whereas, we can reassign the characters of the array.

3.
12/14/2025
Example 1
 #include<stdio.h>
 #include <string.h>
 int main(){
 char ch1[9]={‘C', ‘O', ‘M', ‘P', ‘U', ‘T', ‘E', ‘R', '\0'};
 char ch2[9]=“COMPUTER";
 printf("Char Array Value is: %s\n", ch1);
 printf("String Literal Value is: %s\n", ch2);
 return 0;
 }
 Output

4.
12/14/2025
Traversing String
 Traversing string is somewhat different from the traversing an
integer array.
 We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to
identify the end the string and terminate the loop.
 Hence, there are two ways to traverse a string: By using the length
of string and By using the null character.

5.
12/14/2025
1. Traversing String by Using Length of String
 Example of counting the number of vowels by using the null
character.
 #include<stdio.h>
 void main ()
 {
 char s[11] = “COMPUTERCS";
 int i = 0;
 int count = 0;
 while(i<11)
 {
 if(s[i]==‘A' || s[i] == ‘E' || s[i] == ‘I' || s[i] == ‘O' || s[i] == ‘U')
 {
 count ++;
 }
 i++;
 }
 printf("The number of vowels %d",count); }
 Output: The number of vowels 4 6.
12/14/2025
2. Traversing String by Using Null Character
 #include<stdio.h>
 void main ()
 {
 char s[11] = " COMPUTERCS ";
 int i = 0;
 int count = 0;
 while(s[i] != NULL)
 {
 if(s[i]==‘A' || s[i] == ‘E' || s[i] == ‘I' || s[i] == ‘O' || s[i] == ‘U')
 {
 count ++;
 }
 i++;
 }
 printf("The number of vowels %d", count);
 }
 Output: The number of vowels 4
7.
12/14/2025
Accepting string as the Input
 Till now, we have used scanf to accept the input from the user.
 However, it can also be used in the case of strings but with a
different scenario.
 Consider the below code which stores the string while space is
encountered.
 #include<stdio.h>
 void main ()
 {
 char s[20];
 printf("Enter the string?");
 scanf("%s",s);
 printf("You entered %s",s);
 }
 Output:
 Enter the string? Computer Science is the best

 You entered javatpoint 8.


12/14/2025
Accepting string as the Input
 It is clear from the output that, the above code will not work for
space separated strings.
 To make this code working for the space separated strings, the
minor changed required in the scanf function, i.e., instead of
writing scanf("%s",s), we must write: scanf("%[^\n]s", s) which
instructs the compiler to store the string s while the new line (\n) is
encountered.

9.
12/14/2025
Accepting string as the Input
 Let's consider the following example to store the space-separated
strings.
 #include<stdio.h>
 void main ()
 {
 char s[20];
 printf("Enter the string?");
 scanf("%[^\n]s",s);
 printf("You entered %s",s);
 }
 Output:
 Enter the string? Computer Science is the best

 You entered javatpoint


 Here we must also notice that we do not need to use address of (&)
operator in scanf to store a string since string s is an array of
characters and the name of the array, i.e., s indicates the base 10.
12/14/2025
Some Important Points w.r.t. String
 The compiler doesn't perform bounds checking on the character
array. Hence, there can be a case where the length of the string can
exceed the dimension of the character array which may always
overwrite some important data.
 Instead of using scanf, we may use gets() which is an inbuilt
function defined in a header file string.h. The gets() is capable of
receiving only one string at a time.

11.
12/14/2025
C gets() Function
 The gets() function enables the user to enter some characters
followed by the enter key.
 All the characters entered by the user get stored in a character array.
 The null character is added to the array to make it a string.
 The gets() allows the user to enter the space-separated strings. It
returns the string entered by the user.
 Declaration:
char[] gets(char[]);
 #include<stdio.h>
 void main ()
 {
 char s[30];
 printf("Enter the string? ");
 gets(s);
 printf("You entered %s",s);
 }
 Output:
 Enter the string? jComputer is the best 12.
12/14/2025
Drawbaack of C gets() Function
 The gets() function is risky to use since it doesn't perform any array
bound checking and keep reading the characters until the new line
(enter) is encountered.
 It suffers from buffer overflow, which can be avoided by using
fgets().
 The fgets() makes sure that not more than the maximum limit of
characters are read.
 Consider the following example.
 #include<stdio.h>
 void main()
 {
 char str[20];
 printf("Enter the string? ");
 fgets(str, 20, stdin);
 printf("%s", str);
 }
 Output:
 Enter the string? Computer is the best Subject
 Computer is the b 13.
12/14/2025
C puts() Function
 The puts() function is very much similar to printf() function.
 The puts() function is used to print the string on the console which
is previously read by using gets() or scanf() function.
 The puts() function returns an integer value representing the
number of characters being printed on the console.
 Since, it prints an additional newline character with the string,
which moves the cursor to the new line on the console, the integer
value returned by puts() will always be equal to the number of
characters present in the string plus 1.
 Syntax:
int puts(char[])

14.
12/14/2025
C puts() Function
 Let's see an example to read a string using gets() and print it on the
console using puts().
 #include<stdio.h>
 #include <string.h>
 int main(){
 char name[50];
 printf("Enter your name: ");
 gets(name); //reads string from user
 printf("Your name is: ");
 puts(name); //displays string
 return 0;
 }
 Output:
 Enter your name: Raza Haidri
 Your name is: Raza Haidri

15.
12/14/2025
C String Functions
 There are many important string functions defined in "string.h"
library.
No. Function Description
1 strlen(string_name) returns the length of string name.
copies the contents of source string to
2 strcpy(destination, source)
destination string.
concats or joins first string with second
3 strcat(first_string, second_string) string. The result of the string is stored
in first string.
compares the first string with second
4 strcmp(first_string, second_string) string. If both strings are same, it
returns 0.
5 strrev(string) returns reverse string.

6 strlwr(string) returns string characters in lowercase.

7 strupr(string) returns string characters in uppercase.


16.
12/14/2025
1. strlen() Function
 The strlen() function returns the length of the given string. It
doesn't count null character '\0’.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char ch[20]={‘R', ‘A', ‘Z', ‘A’, ‘H', ‘A', ‘I', ‘D', ‘R', ‘I', '\0'};
 printf("Length of string is: %d",strlen(ch));
 return 0;
 }
 Output
 Length of string is: 10

17.
12/14/2025
Program to find length of string using user defined
Function.
 #include <stdio.h>
 #define MAX_SIZE 100 // Maximum size of the string
 int main()
 {
 char text[MAX_SIZE]; /* Declares a string of size 100 */
 int i;
 int count= 0;
 printf("Enter any string: "); /* Input a string from user */
 gets(text);
 /* Iterate till the last character of string */
 for(i=0; text[i]!='\0'; i++)
 {
 count++;
 }
 printf("Length of '%s' = %d", text, count);
 return 0; } 18.
12/14/2025
2. strcpy() Function
 The strcpy(destination, source) function copies the source string in
destination.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char ch[20]={‘R', ‘A', ‘Z', ‘A’, ‘H', ‘A', ‘I', ‘D', ‘R', ‘I', '\0'};
 char ch2[20];
 strcpy(ch2,ch);
 printf("Value of second string is: %s",ch2);
 return 0;
 }
 Output
 Value of second string is: RAZAHAIDRI

19.
12/14/2025
2. C program to copy one string to another string using
user defined Function
 #include <stdio.h>
 #define MAX_SIZE 100 // Maximum size of the string
 int main()
 {
 char text1[MAX_SIZE];
 char text2[MAX_SIZE];
 int i;
 /* Input string from user */
 printf("Enter any string: ");
 gets(text1);
 /* Copy text1 to text2 character by character */
 for(i=0; text1[i]!='\0'; i++)
 {
 text2[i] = text1[i];
 }
20.
12/14/2025
2. C program to copy one string to another string using
user defined Function
 //Makes sure that the string is NULL terminated
 text2[i] = '\0';
 printf("First string = %s\n", text1);
 printf("Second string = %s\n", text2);
 printf("Total characters copied = %d\n", i);
 return 0;
 }

21.
12/14/2025
3. strcat() Function
 The strcat(first_string, second_string) function concatenates two
strings and result is returned to first_string.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
 char ch2[10]={'c', '\0'};
 strcat(ch,ch2);
 printf("Value of first string is: %s",ch);
 return 0;
 }
 Output
 Value of first string is: helloc

22.
12/14/2025
3. C program to concatenate two strings using user
defined Function
 #include <stdio.h>
 int main() {
 char s1[100] = "programming ", s2[] = "is awesome";
 int length, j;
 // store length of s1 in the length variable
 length = 0;
 while (s1[length] != '\0') {
 ++length;
 }
 // concatenate s2 to s1
 for (j = 0; s2[j] != '\0'; ++j, ++length) {
 s1[length] = s2[j];
 }
 // terminating the s1 string
 s1[length] = '\0';
 printf("After concatenation: "); puts(s1); return 0; } 23.
12/14/2025
4. strcmp() Function
 The strcmp(first_string, second_string) function compares two
string and returns 0 if both strings are equal.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char str1[20],str2[20];
 printf("Enter 1st string: ");
 gets(str1);//reads string from console
 printf("Enter 2nd string: ");
 gets(str2);
 if(strcmp(str1,str2)==0)
 printf("Strings are equal");
 else
 printf("Strings are not equal");
 return 0;
 }
 Output
24.
12/14/2025  Enter 1st string: hello, Enter 2nd string: hello. Strings are equal
4. C program to compare two strings using user defined
Function
 #include <stdio.h>
 #define MAX_SIZE 100 // Maximum string size
 /* Compare function declaration */
 int compare(char * str1, char * str2);
 int main()
 {
 char str1[MAX_SIZE], str2[MAX_SIZE];
 int res;
 /* Input two strings from user */
 printf("Enter first string: ");
 gets(str1);
 printf("Enter second string: ");
 gets(str2);

25.
12/14/2025
4. C program to compare two strings using user defined
Function
 /* Call the compare function to compare strings */
 res = compare(str1, str2);
 if(res == 0)
 {
 printf("Both strings are equal.");
 }
 else if(res < 0)
 {
 printf("First string is lexicographically smaller than
second.");
 }
 else
 {
 printf("First string is lexicographically greater than
second.");
 } return 0; } 26.
12/14/2025
4. C program to compare two strings using user defined
Function
 /**
 * Compares two strings lexicographically. Returns 0 if both
strings are equal, negative if first string is smaller
otherwise returns a positive value */
 int compare(char * str1, char * str2)
 {
 int i = 0;
 /* Iterate till both strings are equal */
 while(str1[i] == str2[i])
 {
 if(str1[i] == '\0' && str2[i] == '\0')
 break;
 i++;
 }
 // Return the difference of current characters.
 return str1[i] - str2[i]; 27.
12/14/2025
5. strrev() Function
 The strrev(string) function returns reverse of the given string. Let's
see a simple example of strrev() function.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char str[20];
 printf("Enter string: ");
 gets(str);//reads string from console
 printf("String is: %s",str);
 printf("\nReverse String is: %s",strrev(str));
 return 0;
 }
 Output
 Enter string: razahaidri
 String is: razahaidri
 Reverse String is: irdiahazar
28.
12/14/2025
6. strlwr() and strupr() Function
 The strlwr(string) function returns string characters in lowercase.
Let's see a simple example of strlwr() function.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char str[20];
 printf("Enter string: ");
 gets(str);//reads string from console
 printf("String is: %s",str);
 printf("\nLower String is: %s",strlwr(str));
 printf("\nUpper String is: %s",strlupr(str));
 return 0;
 }
 Output
 Enter string: RAZA Haidri
 String is: RAZA Haidri
 Lower String is: razahaidri 29.
12/14/2025
7. strstr() Function
 The strstr() function returns pointer to the first occurrence of the
matched string in the given string.
 It is used to return substring from first match till the last character.
 Syntax:
char *strstr(const char *string, const char *match)
 string: It represents the full string from where substring will be
searched.
 match: It represents the substring to be searched in the full string.
 #include<stdio.h>
 #include <string.h>
 int main(){
 char str[100]="this is javatpoint with c and java";
 char *sub;
 sub=strstr(str,"java");
 printf("\nSubstring is: %s",sub);
 return 0;
 }
 Output
 javatpoint with c and java
30.
12/14/2025
Homework
 Write a C program to find total number of alphabets, digits or
special character in a string.
 Write a C program to count total number of vowels and consonants
in a string.
 Write a C program to count total number of words in a string.
 Write a C program to find reverse of a string.
 Write a C program to check whether a string is palindrome or not.
 Write a C program to trim both leading and trailing white space
characters from given string.
 Write a C program to remove all extra blank spaces from given
string.

31.
12/14/2025
References
 Yashwant Kanetkar, Let us C”, BPB Publications.
 B. Kernighan and D. Ritchie, The ANSI C Programming Language,
PHI.
 E. Balagurusamy, “Programming in ANSI C”, TMH.
 Kernighan and Dennis M. Ritchie, The C Programming Language,
Pearson Education.
 [Link]
 [Link]
 [Link]
[Link]

32.
12/14/2025

You might also like