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

String Handling on

The document provides an extensive overview of string handling in C and C++, emphasizing the use of character arrays and null terminators for string operations. It covers various string manipulation functions, including copying, concatenation, and case conversion, as well as how to implement these operations without built-in functions. Additionally, it touches on file handling and the importance of managing data input and output effectively.

Uploaded by

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

String Handling on

The document provides an extensive overview of string handling in C and C++, emphasizing the use of character arrays and null terminators for string operations. It covers various string manipulation functions, including copying, concatenation, and case conversion, as well as how to implement these operations without built-in functions. Additionally, it touches on file handling and the importance of managing data input and output effectively.

Uploaded by

manojrajora.vgi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

String handling in C & C++ - String Handling is the Major Topic for Interview.

in written / Interview - we have Major Questions from String Handling.

char - single char - it can store only single char


char c = 'A'; char c; c = getch(); - contain/store only one char.

String - group of chars. for implement/use string in C & C++, we have concept
of char array.
** means C & C++ ke inside string store karne ke liye alag se koi data type
nahi, for that we need to use char array. but in java we have String class for
store the String,

char nm[10]; - we can store 10 chars string. - means we can store Max 10 chars
string. 9 chars + 1 is the string terminator char / null char &
that is represent with - '\0'

Q- null char memory leta hai ya nahi? - ans - always says lete hai.
Q- we have char ar[10] - how many char string we can store inside ar array?
Ans - 9 char string + 1 char/index reserved for null char , null char
represent '\0' or we can use 0 also

** \0 is major use in programming, jaha koi bhi String pe operation perform


karna hai without any function for that we need to use null char - u have
only option of null char for reslove any type of string related problem.

char ar[10]; - strcpy(ar,"Gaurav"); ar = "Gaurav";


char ar[10]; - ar = "Gaurav"; - wrong way, - for string initialize we need to
use strcpy() function or we can initialize String at declare
time or initialize with runtime inputs for string input, we
have
1 - scanf("%s",nm); - input accept until space (space se pahle
wala string accept karega)
2 - gets(nm); - accept input until enter key press
- jab tak enter nahi press karoge tab tak ka input accept karega

ar[0] = 'G' ;
ar[1] = 'a' ;
ar[2] = 'u' ;
ar[3] = 'r' ;
ar[4] = 'a' ;
ar[5] = 'v' ;
ar[6] = '\0' ; - NULL char, string terminator char.

NULL char Major use for work with String - means NULL char String handling me
major role play karta hai.

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 1
nm = "Gaurav"; - wrong way, we can't initialize String with = operator , for
that we need to strcpy() function.

strcpy(nm,"Gaurav"); now nm = "Gaurav";

String Handling in C & C++ -

for string handling in C & C++ we have string.h header file, that contain the
functions for string handling.

** all string handling functions prefix with str word - strcat / strrev /
strcpy / strlen / strupr / strlwr / strcmp / strcmpi / strncmp / strncmpi()
- Total we have 10 functions
6 functions for normal operations. - strcpy() , strcat(), strupr(), strlwr(),
strlen(), strrev().
4 functions for String Compare - strcmp / strcmpi / strncmp / strncmpi()

** String handling problem solving without using any in build/pre define


function. (80-90% cases written/machine test/interview)

1st - strcpy(str1,str2) - for string copy.

char nm[15];
nm = "Gaurav"; - wrong way in C & C++.
strcpy(nm, "Gaurav"); now nm is = "Gaurav"

we want to copy string without using any function.

char arr[10];
char ar[] = "Gaurav"; - declare time.
gets(ar); / scanf("%s",ar); - for run time input.

ar = "Gaurav";

- for String copy without using strcpy() function -

ar = "Gaurav";
int ctr = 0;
while(ar[ctr] != '\0') // while not end of the String.
{
arr[ctr] = ar[ctr]; // copy char by char in arr from ar index.
ctr ++;
}
arr[ctr] = '\0';

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 2
2nd - strcat(str1,str2) - for String concat
int a = 10; - NOW WE WANT TO ADD 5 VALUE IN a, a = a + 5; / a += 5; NOW a = 15

nm = "Gaurav"; - we want to add Kumar in nm


strcat(nm," Kumar"); - nm = "Gaurav Kumar";

3rd - strupr(str); - to convert string into upper case

char ar[] = "Gaurav Kumar";


strupr(ar);
printf("\nString in upper case %s",ar);

output - String in upper case GAURAV KUMAR

- convert String in Upper case without using any function -

int x;
clrscr();
x = 0;
while(ar[x]!='\0') // while not end of string,means jab tak null char na ho
{
if(ar[x]>='a' && ar[x]<='z') // means small a to z hai to
ar[x] = ar[x]-32;
x++;
}
printf("\nString in upper case %s",ar);

output - String in upper case GAURAV KUMAR

// program for convert string into upper case with strupr() function & without strupr()
function - with own algo
void main()
{
char ar[] = "Gaurav Kumar";
int x;
clrscr();
/*
strupr(ar);
printf("\nString in upper case %s",ar);
*/
x = 0;
while(ar[x]!='\0')
{
if(ar[x]>='a' && ar[x]<='z')
ar[x] = ar[x]-32;
x++;
}
printf("\nString in upper case %s",ar);
getch();
}
C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 3
4th - strlwr(str); - to convert string into lower case

char ar[] = "Gaurav Kumar";


strlwr(ar);

ASCII code - A - 65 to Z - 90
a - 97 to z - 122
-----------------
32 32

lower to upper cast - -32 / upper to lower case casting - +32

- convert String in Upper case without using any function -

int x;
clrscr();
x = 0;
while(ar[x]!='\0')
{
if(ar[x]>='A' && ar[x]<='Z')
ar[x] = ar[x]+32;
x++;
}
printf("\nString in Lower case %s",ar);

5th - strrev() - for string reverse


char ar[] = "malayalam";
strrev(ar);
printf("\nString in reverse %s",ar);

String reveser without using any function -

// loop for calculate the length of String


x = 0;
while(ar[x]!='\0')
x++;

printf("String in Reverse - ");


for(i=x-1;i>=0;i--) // loop for print in reverse
printf("%c",ar[i]);

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 4
String reverse without any function & store in a variable

ctr = 0;
while(ar[ctr]!='\0') // loop for count String length.
ctr ++;

for(i=0,j=ctr-1;i<ctr;i++,j--); // loop for String reverse


arr[i] = ar[j];
arr[i]= '\0';

ar = Babu
i = 0 j = 4
ar[0] = 'B'; ctr = 1 arr[i=0] = ar[j = 3]= 'u'
ar[1] = 'a'; ctr = 2 arr[i=1] = ar[j = 2]= 'b'
ar[2] = 'b'; ctr = 3 arr[i=2] = ar[j = 1]= 'a'
ar[3] = 'u'; ctr = 4 arr[i=3] = ar[j = 0]= 'B'
ar[4] = '\0'; ctr = 5 arr[i=4] = '\0';

// program for check String is Palindrome or not - with own algo


void main()
{
char str[] = "malayalam";
int i,len = 0,flag=1;
clrscr();
while(str[len] != '\0')
len++;

for(i = 0; i <= len/2; i++) // length ke half tak


{
if(str[i] != str[len - i - 1])
{
flag = 0;
break;
}
}
if(flag)
printf("\n %s is a Palindrome String", str);
else
printf("\n %s is Not a Palindrome String", str);
getch();
}

Dry Run -

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 5
malayalam
012345678

len = 9;

compare -
str[i=0] = str[(len=9)-(i=0)-1 = 8] compare - m = m
str[i=1] = str[(len=9)-(i=1)-1 = 7] compare - a = a
str[i=2] = str[(len=9)-(i=2)-1 = 6] compare - l = l
str[i=3] = str[(len=9)-(i=3)-1 = 5] compare - a = a
str[i=4] = str[(len=9)-(i=4)-1 = 4] compare - y = y

6th - int strlen(str); - return the length of String.


nm = "Gaurav";
x = strlen(nm); x = 9 - C & C++

// findout length of String in C without using strlen function.


int ctr = 0;
while(ar[ctr]!='\0') // string not empty - ctr increment karo.
ctr++;
printf("String length is - %d",ctr);

7th - int strcmp(str1,str2) - compare 2 Strings without ignore case - means


case sensitive.

it return - 0 - if both strings r equals


+ve - if 1st string is greater
-ve - if 1st string is small.

** compare with char by char(with ASCII code) & return the diff of ASCII code.

ASCII code - A - 65 to Z - 90
a - 97 to z - 122

a = "Ankit"; b = "Chintu";
if(strcmp(a,b)>0) - -2 - condition false
if(strcmp(b,a)>0) - +2 - condition true

8th - int strcmpi(str1,str2) - compare 2 Strings with ignore case - means case
in-sensitive.

it return - 0 - if both strings r equals


+ve - if 1st string is greater
-ve - if 1st string is small.

** compare with char by char(with ASCII code) & return the diff of ASCII code.

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 6
a = "ankit"; b = "ANKIT";
if(strcmpi(a,b)==0) - 0 - true
a = "ANKIT", b "Chintu";
if(strcmpi(a,b)<0) - -2 - condition true

if(strcmpi(b,a)>0) - +2 - condition true

* it internally convert into one case - may be upper or lower then compare it
char by char

// Enter 10 names & display in ascending order

#include<stdio.h>
#include<conio.h>
#define MAX 10
void main()
{
char tmp[20],nm[MAX][20]; //10 rows- 10names, each name contain max 20 chars
int i,j;
clrscr();
for(i=0;i<MAX;i++)
{
printf("Plz Enter name %d : ",i+1);
gets(nm[i]);
strupr(nm[i]);
}
// for sorting - selection sort.
for(i=0;i<MAX-1;i++)
{
for(j=i+1;j<MAX;j++)
{
if(strcmp(nm[i],nm[j])>0) // swap 2 strings with 3rd var.
{
strcpy(tmp,nm[i]);
strcpy(nm[i],nm[j]);
strcpy(nm[j],tmp);
}
}
}
// for display
for(i=0;i<MAX;i++)
printf("\nWelcome %s",nm[i]);
getch();
}

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 7
9th - int strncmp(str1,str2,noc) - compare 2 Strings with no of chars -
without ignore case - means case sensitive.
it return - 0 - if both strings r equals
+ve - if 1st string is greater
-ve - if 1st string is small.
** compare with char by char(with ASCII code) & return the diff of ASCII code.

a = "Amandeep";
b = "Aman Singh";
if(strncmp(a,b,4)==0) {} - compare starting 4 chars - true

10th - int strncmpi(str1,str2,noc) - compare 2 Strings with no of chars with


ignore case - means case insensitive.

it return - 0 - if both strings r equals


+ve - if 1st string is greater
-ve - if 1st string is small.
** compare with char by char(with ASCII code)
& return the diff of ASCII code.

a = "AMANDEEP";
b = "Aman Singh";
if(strncmpi(a,b,4)==0) {} true - compare starting 4 chars with ignore case

for String compare in C we have 4 funcion - strcmp(str1,str2),


strcmpi(str1,str2), strncmp(str1,str2,noc), strncmpi(str1,str2,NOC)

// compare 2 Strings without any function - with own algo - using for loop

- using for loop -


0123 4 0123 4
str1 = "Aman\0" str1 = "Aman\0" 4th index - null char - value = 0
str2 = "Aman\0" str2 = "Aman Ji" 4th index - space - value = 32

for(i = 0; str1[i] == str2[i] && str1[i] != '\0'; i++);


if(str1[i] > str2[i])
printf("\n str1 is Greator than str2");
else if(str1[i] < str2[i])
printf("\n str2 is Greator than str1");
else
printf("\n str1 is Equal to str2");

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 8
FILE I/O
Why file handling is needed ?

In programming, we may require some specific input data to be generated several


numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again. However,
if we need to do so, we may store it onto the local file system which is volatile
and can be accessed every time. Here, comes the need of file handling in C. File
handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program.
Real life situations involve large volume of data and in such cases, the console
oriented I/O operations pose two major problems:
 It becomes complex / bulky and time consuming to handle large volumes of data
through terminals.
 The entire data is lost when either the program is terminated or computer is
turned off therefore it is necessary to have more flexible approach where data
can be stored.
File Operations - Different operations:
-> Creation of a new file
-> Opening an existing file
-> Reading from a file
-> Writing to a file
-> Moving to a specific location in a file
-> Closing a file

File opening Modes :


r - opens a text file in read mode
w - opens a text file in write mode
a - opens a text file in append mode
r+ - opens a text file in read and write mode
w+ - opens a text file in read and write mode
a+ - opens a text file in read and write mode
rb - opens a binary file in read mode
wb - opens a binary file in write mode
ab - opens a binary file in append mode
rb+ - opens a binary file in read and write mode
wb+ - opens a binary file in write and read mode
ab+ - opens a binary file in read and write mode

* searches file, if the file is opened successfully fopen() loads into


memory. if the file can't be open fopen() function returns NULL

Types of files - we have 2 types of file -


1. Text File
2. Binary File.
C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 9
Functions for file handling

There are many functions in the C library to open, read, write, search and
close the file. A list of file functions are given below:

No. Function Description


1. fopen() - opens new or existing file
2. fprintf() - write formatted data into the file
3. fscanf() - reads formatted data from the file
4. fputc() - writes a character into the file
5. fgetc() - reads a character from file
6. fgets() - read string from a file.
7. fputs() - write String in a file.
8. feof() - check file end of file or not, if yes then it return true else
return false.
9. fclose() - closes the file
10. fseek() - sets the file pointer to given position
11. fputw() - writes an integer to file
12. fgetw() - reads an integer from file
13. ftell() - returns current position
14. rewind() - sets the file pointer to the beginning of the file

** all file handling function prefix with f

Steps for processing the file


 Declare a file pointer variable.

 Open a file using fopen() function.

 Process the file using the suitable function.

 Close the file using fclose() function.

File handling in short -

if we want to read / write data from / in a file for that we can use
file handling.

we have 2 operations in File- 1- input - for read data from a file


2- output - write data in a file.

steps for file Handling C -

1st - we need to declare FILE type pointer variable

FILE *f;

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 10
2nd - now open an file in input or output mode with - fopen() function.
FILE* fopen(filename,mode);
mode - r - read mode - open an file in input mode
r+ - read & write mode - 1st read then write
w - write mode - open an file in output mode
w+ - write & read - 1st write then we can read
a - append mode - open an file in append mode (exiting + new data)
a+ - append & read - 1st append then read
b - binary mode - open an file in binary mode
x - if file already exist then not create.
f = fopen("c:/F1.c","r");

3rd - check file pointer end of the file or not..

feof(file) - file end of the file - return true if file end of the file.

4th - for read & write

mode read write


* char by char fgetc(file) fputc(char,file)
c = fgetc(r); fputc(c,w);
* line by line fgets(char[],NOC,file) fputs(char[],file);
fgets(ar,80,r); fputs(ar,w);
* with formats fprintf(file,format,var) fscanf(file,format,var);

* for struct fwrite((char*)&struct,sizeof(struct),NOR,file)


fread((char*)&struct,sizeof(struct),NOR,file)
ex - fread((char*)&s,sizeof(s),1,f); fwrite((char*)&s,sizeof(s),1,f);
** fread() & fwrite() Major use in project development.
5th - for file close, we have fclose() function
fclose(file);

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 11
// to read own source code & display on console window.
#include<stdio.h>
void main()
{
FILE *r;
char c;
clrscr();
r = fopen("F1.c","rb"); // open F1 file in input + binary mode
if(r==NULL)
printf("Sorry ur file not found for input...");
else {
while(1)
{
c = fgetc(r);
if(feof(r)) break;
delay(50); // 1000ms = 1 sec
printf("%c",c);
}
fclose(r);
}
getch();
}

// to read own source code & display on console + write in a file also
#include<stdio.h>
void main()
{
FILE *r,*w;
char c;
clrscr();
r = fopen("F1.c","rb"); // open F1 file in input + binary mode
w = fopen("gaurav.txt","wb"); // open aman.txt file in output + binary mode
if(r==NULL)
printf("Sorry ur file not found for input...");
else {
while(1)
{
c = fgetc(r);
if(feof(r)) break;
fputc(c,w); // write char in w file
delay(50); // 1000ms = 1 sec
printf("%c",c);
}
fclose(r);
fclose(w);
}
getch();
}

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 12
// read & write data line by line
#include<stdio.h>
void main()
{
FILE *r,*w;
char ar[80];
clrscr();
r = fopen("F1.c","rb"); // open F1 file in input + binary mode
w = fopen("gaurav.txt","wb"); // open aman.txt file in output + binary mode
if(r==NULL)
printf("Sorry ur file not found for input...");
else {
while(1) {
fgets(ar,80,r); // read 80 char from r file & stored inside ar array
if(feof(r)) break;
fputs(ar,w); // write char in w file
delay(50); // 1000ms = 1 sec
printf("%s",ar);
}
fclose(r);
fclose(w);
}
getch();
}

C String Handling & File Handling Notes - on 23-01-2025 by Manoj Rajora Page 13

You might also like