String after Backspaces in C++
In this tutorial, we will learn how to backspace a letter from a word in C++. Something like erasing a letter as a backspace does, but this time with C++. Let us start with an introduction.
Introduction:
Given a string S contains letters and #.
The ‘#’ represents a backspace.
The task is to print a new string without ‘#’.
Example:
Input S=“Codee#SS#peee#dd#yy#“.
Output S=CodeSpeedy.
Algorithm: to backspace a letter from a string in C++
- Traverse the string S.
- If any char except ‘#’ is found push it at back in deque
- If the char ‘#’ is found pop. A char from the back of the deque.
- Finally, pop all elements from front deque to make a new string.
It is a simple algorithm we can easily get through to the program.
No much explanation is needed to write this program this algorithm is enough.
In this program we use 3 functions to work out there are InsertRear, DeleteRear, DeleteFront.Let us start with InsertRear function the logic in this function is if the front is equal to -1, then rear and front equal to 0. The input is inserted into deque[rear] else rear is incremented by 1.
In DeleteFront function the logic is if the front is equal to rear, front and rear equal to -1 else Front is incremented by 1. In DeleteRear function, the logic is if front equal to the rear then front and rear are equal to -1 else rear is decremented by 1.
Program:
#include<iostream>
#define MAX 100
using namespace std;
char Deque[MAX];
int front =-1,rear=-1;
void InsertRear(char item)
{
int i;
if(front==-1)
{
rear=front=0;
Deque[rear]=item;
return;
}
else
{
rear++;
Deque[rear]=item;
}
}
void DeleteFront()
{
char item;
item=Deque[front];
cout<<item;
if(front==rear)
{
front=rear=-1;
}
else
front++;
}
void DeleteRear()
{
if(front==rear)
front=rear=-1;
else
rear--;
}
int main()
{
char s[100]="Codee#SS#peee#dd#yy#";
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]!='#')
InsertRear(s[i]);
else if(front !=-1)
DeleteRear();
}
while(front!=-1)
{
DeleteFront();
}
return 0;
}Output:
CodeSpeedy
Hope this will help you to understand how to backspace a letter from a word in C++.
Also read:
Leave a Reply