Vous êtes sur la page 1sur 34

GeeksforGeeks

Home Arrays Q&A Interview Corner Bit Magic C/C++ Puzzles

Log in

A computer science portal for geeks


Ask a question Articles Contribute GFacts GATE Algorithms MCQ C Misc C++ Books About us Trees Linked Lists Output Strings

Remove b and ac from a given string

May 19, 2013


Searc h

Given a string, eliminate all b and ac in the string, you have to replace them in-place, and you are only allowed to iterate over the string once. (Source Google Interview Question) Examples:
acbac aaac ababac bbbbd ==> ==> ==> ==> "" aa aa d Interview Experiences Advanced Data Structures Dynamic Programming Greedy Algorithms Backtracking Pattern Searching Divide & Conquer Graph Mathematical Algorithms Recursion Java

The two conditions are: 1. Filtering of all b and ac should be in single pass 2. No extra space allowed. The approach is to use two index variables i and j. We move forward in string using i and add characters using index j except b and ac. The trick here is how to track a before c. An interesting approach is to use a two state machine. The state is maintained to TWO when previous character is a, otherwise state is ONE. 1) If state is ONE, then do NOT copy the current character to output if one of the following conditions is true a) Current character is b (We need to remove b) b) Current character is a (Next character may be c) 2) If state is TWO and current character is not c, we first need to make sure that we copy the previous character a. Then we check the current character, if current character is not b and not a, then we copy it to output. // A C++ program to remove "b" and 'ac' from input string #include <iostream> using namespace std;

GeeksforGeeks
Like 28,266 people like GeeksforGeeks.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

using namespace std; #define ONE 1 #define TWO 2 // The main function that removes occurences of "a" and "bc" in input string void stringFilter(char *str) { // state is initially ONE (The previous character is not a) int state = ONE; // i and j are index variables, i is used to read next character of input // string, j is used for indexes of output string (modified input string) int j = 0; // Process all characters of input string one by one for (int i = 0; str[i] != '\0'; i++) { /* If state is ONE, then do NOT copy the current character to output if one of the following conditions is true ...a) Current character is 'b' (We need to remove 'b') ...b) Current character is 'a' (Next character may be 'c') */ if (state == ONE && str[i] != 'a' && str[i] != 'b') { str[j] = str[i]; j++; } // If state is TWO and current character is not 'c' (otherwise // we ignore both previous and current characters) if (state == TWO && str[i] != 'c') { // First copy the previous 'a' str[j] = 'a'; j++; // Then copy the current character if it is not 'a' and 'b' if (str[i] != 'a' && str[i] != 'b') { str[j] = str[i]; j++; }

Fac ebook s oc ial plugin

Popular Posts
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST

// Change state according to current character state = (str[i] == 'a')? TWO: ONE;

// If last character was 'a', copy it to output if (state == TWO)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

if (state == TWO) { str[j] = 'a'; j++; } // Set the string terminator str[j] = '\0';

/* Driver program to check above functions */ int main() { char str1[] = "ad"; stringFilter(str1); cout << str1 << endl; char str2[] = "acbac"; stringFilter(str2); cout << str2 << endl; char str3[] = "aaac"; stringFilter(str3); cout << str3 << endl; char str4[] = "react"; stringFilter(str4); cout << str4 << endl; char str5[] = "aa"; stringFilter(str5); cout << str5 << endl; char str6[] = "ababaac"; stringFilter(str6); cout << str6 << endl; } return 0;

Output:
ad aa ret aa
Follow @Geeksforgeeks
Are you a developer? Try out the HTML to PDF API

1,562 follow ers

open in browser PRO version

pdfcrowd.com

aaa

An extension of above problem where we dont want ac in output at all: The above code looks fine and seems to handle all cases, but what if input string is aacacc, the above code produces output as ac which looks correct as it removes consecutive occurrences of a and c. What if the requirement is to not have an ac in output string at all. Can we modify the above program to produce output as empty string for input aacacc and produce output as d when input is abcaaccd? It turns out that it can also be done with given restrictions. The idea is simple. We need to add following lines inside for loop of the above program. if (j>1 && str[j-2] == 'a' && str[j-1] =='c') j = j-2; See this for different test cases of modified program. This article is contributed by Varun Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Like 52 Tw eet 3 Share

507

Subscribe

Recent Comments
Nikhil on Remove b and ac from a given string krishh on Google Placement Questions krishh on Google Placement Questions Anon on Boundary Traversal of binary tree Mangal on Shadowing of static functions in Java raghvendra on Find a peak element Raunak Lakhwani on Google Placement Questions Amit Singh on Find a pair with given sum in a Balanced BST

CPP String Function Java C++ Array

You may also like following posts 1. Remove all duplicates from the input string. 2. Print all the duplicates in the input string.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

3. Remove characters from the first string which are present in the second string 4. Count words in a given string 5. String matching where one string contains wildcard characters
[fbcomments] 18 comments Nitin Panwar Indian Institute of Information Technology and Management, Gwalior #include<stdio.h> #include<string.h> void remove(char *);. void set(char *, int, int);. int main() { char aa1[]="acbac";. char aa2[]="aaac";. char aa3[]="ababac";. char aa4[]="bbbbd";. remove(aa1);. remove(aa2);. remove(aa3);. remove(aa4);. printf("%s\n", aa1);.... See more Reply Like 20 July at 03:26 Tapas Mahanta National Institute of Technology, Warangal #include<iostream> #include<string> using namespace std;. int main() { string s="react"; while((s.find("ac"))!=s.npos) s.erase(s.find("ac"), 2); while((s.find("b"))!=s.npos) s.erase(s.find("b"), 1); cout<<s<<endl; } //tell me if any test cases don't work on this one. Reply Like 6 July at 10:02

Replace AC Array C#

Swapnil Sunil Gondkar Veermata Jijabai Technological Institute (VJTI),MATUNGA,MUMBAI read the question carefully it is given not to iterate over the string again !

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Reply Like 12 July at 02:46 Manisha Barnwal 106 subscribers //another even simpler O(n) solution could be.. /*Given a string, eliminate all b and ac in the string, you have to replace them in-place, and you are only allowed to iterate over the string once*/. #include<stdio.h> void modify(char str[]). {

int i, j,k, count;. ... See more Reply Like 29 June at 14:29 GeeksforGeeks We have added another solution that handles test cases suggested by Ashish & Mohammad Iqubal. Reply 5 Like 19 May at 14:55

Varun Jain Programmer Analyst at Amazon A quick solution for second version of this question is we can add below check either in beginning or loop.

if ( j>1 && str[j-2]=='a' && str[j-1] =='c' ).

j = j-2;. This check will keep output strings free from 'ac'. Reply Like 19 May at 14:46 Mohammad Iqubal Postgraduate (M.C .A.) at JNU New Delhi what will be the output of the string "abcd"???r are you sure your output will be "d" Reply Like 21 May at 23:58

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Mohammad Iqubal Postgraduate (M.C .A.) at JNU New Delhi void remove_b_and_ac(char *q) { char *p=q; int j=0; if(!*p) return ; while(*p) { if(*p=="b") p++; elseif(*p=="c" && ((p-1)>=q)) { if(*(p-1)=="a") { j=j-1;... See more Reply Like 22 May at 11:14 Virendra Saroj Engineer at SmartPlay Technologies (I) Pvt. Ltd. Mohammad Iqubal elseif(*p=="c") { if(*(p-1)=="a") if first character is C and you r trying to access *(p-1) it will produce some error . Reply Like 22 May at 23:37 View 1 more Varun Jain Programmer Analyst at Amazon So, original question was to remove 'ac' and 'b' from main string which may result 'ac' in final output as happening with mention below two cases. a ac ac c - ac ( two occurrences of ;ac; and both are removed. , result is ac( first 'a' and last 'c' ). a b ca ac cd - acacd ( one occurrence of 'b' and one of 'ac' is removed ). Thanks for your comments because of that we got a second version of question on how to make final output totally 'ac' free. Reply Like 19 May at 14:23 Mohammad Iqubal Postgraduate (M.C .A.) at JNU New Delhi what will be the output of the string "abcd"???r are you sure your output will be "d" Reply Like 21 May at 10:48

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Ashish & Mohammad Iqubal: Thanks for pointing out these cases. We will soon update the post to handle these cases as well. Reply Like 19 May at 13:07 Ashish Aggarwal Bangalore, India Not working with aacacc Reply Like 19 May at 11:44 Mohammad Iqubal Postgraduate (M.C .A.) at JNU New Delhi is it work for the input abcaaccd whose output is d only? Reply Like 19 May at 11:40
Fac ebook s oc ial plugin

32 comments so far
Nikhil says: August 20, 2013 at 9:25 PM In java, Strings are immutable, if I dont konw C much, how w ould i take this up? Reply

penhaunt says: August 15, 2013 at 4:16 PM Why don't you this strategy w hich I got from ABHAY Are you a developer? Try out the HTML to PDF API

open in browser PRO version

pdfcrowd.com

#include<stdio.h> void google( char *s) { int i=0,j; for (j=0;s[j];j++) { if (s[j]!='b') { if (i>0&&s[j]=='c'&&s[i-1]=='a') i--; else s[i++]=s[j]; } } s[i]='\0'; } int main() { char s[]="acbac"; google(s); printf (s); return 0; } Reply

neelkand says: August 12, 2013 at 9:33 PM #include<iostream> using namespace std; void stringFilter(char *str){ int i,j=0,temp=0; for(i=0;str[i]!='\0';i++){ if(str[i]=='a'){ if(temp==1) str[j]='a'; temp=1; } else if(str[i]=='c' && temp==1){ j--; temp=0; continue; } else if(str[i]=='b'){ if(temp==1) temp=0;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

continue; } str[j++]=str[i]; } str[j]='\0'; } int main(){ char str6[50]; cin>>str6; stringFilter(str6); cout << str6 << endl; return 0; } Reply

anim esh bhatia says: August 4, 2013 at 4:18 PM #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[20],str1[20],str2[20]; char *s,*s1,*s2,*s3; printf ("\nEnter string:\n"); gets (str); int i,j,k=0; s=str; s1=str1; s3=str2; while (*s) { if (*s=='b') s=s+1; else if (*s=='a' && *(s+1)=='c') s=s+2; else { *s1=*s; s1++; s++;} } *s1='\0'; s2=str1; while (*s2) { if (*s2=='a' && *(s2+1)=='c')

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

if (*s2=='a' && *(s2+1)=='c') { s2=s2+2; } else { *s3=*s2; s3++; s2++; } } *s3='\0'; printf ("\nAfter removing b and ac,the string is:\n"); printf ("%s",str2); getch(); } Reply

richa_431 says: July 23, 2013 at 2:31 AM //remove "b" and "ac" from a given string #include #include char * remove (char * s) { char * r; int c=0; w hile(s!='\0') { if(*s=='a'&&*(s+1)=='c') { s+=2; continue; } else if(*s=='b') { s++; continue; } else {

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

c++; *(r++)=*(s++); } } *r='\0'; return (r-c); } void main() { char str[100]; clrscr(); printf("Enter the string:"); gets(str); char * s,*r; s=str; r=remove(s); printf("string after removal is:%s",r); getch(); } Reply

AlgoCoder says: July 21, 2013 at 12:27 AM void search_ac_b( char * str, int &i) { if (str[i] == '\0') return ; if (str[i] == 'b') search_ac_b(str, ++i); else if (str[i] == 'a' && str[i+1] == 'c') { i += 2; search_ac_b(str, i); } return ; } void remove ( char * str) { int i = 0; int j = 0; if (str[i] == '\0')

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

if (str[i] == '\0') return ; while (str[i] != '\0') { search_ac_b(str, i); if (str[i] == '\0') break ; str[j] = str[i]; ++j; ++i; } str[j] = '\0'; return ;

Reply

shilendhari says: July 16, 2013 at 4:25 PM a recursive solution #include "stdio.h" #include "stdlib.h" void remove1( char *str) { int i=0,flag=0; char temp; char * new ; new = malloc ( sizeof ( char )); char *new1 = new ; while (*str!='\0') { if (*str=='b') { str++; } else if (*str=='a') { temp=*(str+1); if (temp=='c') { str=str+2; flag++; } else { new [i]=*str; str++; i++; } } else { new [i]=*str; str++;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} main() { char *str; str= malloc ( sizeof ( char )); printf ("enter string"); scanf ("%s",str); remove1(str); return 0; }

} } if (flag==0) return ; else { new [i]='\0'; printf ("\nnew %s",new1); remove1( new ); }

str++; i++;

Reply Bala says: August 2, 2013 at 11:00 PM Your code needs to increment flag even w hen you encounter 'b'. Else it w ont w ork for inputs like 'aaab' or 'abc'. But a neat recursive solution nevertheless !! Reply

adw ait says: July 6, 2013 at 9:59 PM #include<stdio.h> #include<string.h> #define MAX 100 rmacb( char a[]) { int pos,cur,n; pos=cur=0; n= strlen (a); int i; while (pos<n) { label1: if (a[pos]=='b') pos++; else if (a[pos]=='a'&&a[pos+1]=='c') pos=pos+2;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

else

pos=pos+2; if (pos>=1&&a[pos]=='c'&&a[cur-1]=='a') { cur--; pos++; }

else

{ a[cur]=a[pos]; pos++;cur++;

} } a[cur]='\0'; } main() { char a[MAX]; printf ("Enter string:\n"); scanf ("%s",a); rmacb(a); printf ("%s\n",a); } Reply

neokid says: June 22, 2013 at 12:13 PM A non State Machine version: char * remove_b_ac( char * s) { if (s == NULL) return NULL; if ( strlen (s) == 0) return s; int i = 0; int j = 0; int d = 0; while (s[i] != '\0') { // move i to pass over 'b' or 'ac' // remain j to remember the start position while (s[i] == 'b' || s[i] == 'a' && s[i+1] == 'c') { if (s[i] == 'b') ++i; if (s[i] == 'a' && s[i+1] == 'c') { ++i; ++i;} } // if i is larger than j, it means 'b' or 'ac' are found d = i - j; if (d > 0) { // move those following chars for ( ; s[i] != '\0'; ++i) { s[i-d] = s[i]; }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} ++j; i = j;

} s[i-d] = '\0';

Reply

firoz says: June 20, 2013 at 3:26 PM #include<stdio.h> void main() { int j=0,i=0; char ar[20]; clrscr(); printf ("enter string:\t"); gets (ar); for (i=0;ar[i]!='\0';i++) { if (ar[i]=='a' && ar[i+1]!='\0' && ar[i+1]=='c') { i=i+1; } else if (ar[i]!='b') { ar[j]=ar[i]; j++; }

} ar[j]='\0'; puts (ar); getch();

Reply

Balasubram anian says: May 30, 2013 at 11:39 PM I think the follow ing code w ould do the same as done by the first code w ithout involving states(w hich is a bit confusing) void removeChars( char *s){ if (!s) return ; int len= strlen (s); int i=0,j=0; while (j<len){

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

while (j<len){ if (s[j]=='b') ++j; else if (j<len-1 && s[j]=='a' && s[j+1]=='c') j += 2; else s[i++]=s[j++]; } s[i]='\0'; return ;

Reply ultim ate_coder says: June 28, 2013 at 5:30 PM Ur solution seems fine. Thanx for code ! ! ! Reply

Tathagath says: May 26, 2013 at 2:21 PM import re re.sub(r'(b)*(ac)*','',inputString) Reply

Avdut says: May 24, 2013 at 10:25 AM What should be the output w hen the string w ill be "aaaccc" ? Reply ultim ate_coder says: June 28, 2013 at 5:31 PM aacc Reply

vishw anath says:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

May 24, 2013 at 12:56 AM 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 main(){ 5 char *s=( char *) malloc ( sizeof ( char )*100); 6 scanf ("%s",s); 7 //printf("%s",s); 8 int len= strlen (s); 9 int i,j=len+1; 10 for (i=len-1;i>=0;){ 11 >------- if (s[i]=='b'){ 12 >------->------- if (j>len) 13 >------->------->-------j=i; 14 >------->-------i--; 15 >-------} 16 >------- else if (s[i]=='c' && s[i-1]=='a'){ 17 >------->------- if (j>len) 18 >------->------->-------j=i; 19 >------->-------i-=2; 20 >-------} 21 >------- else { 22 >------->------- if (j<len) 23 >------->------->-------s[j--]=s[i]; 24 >------->-------i--; 25 >-------} 26 >------27 } 28 29 printf ("%s",s+j+1); 30 } Reply

Karthik Venkatesw aran says: May 24, 2013 at 12:51 AM #include<stdio.h> #include<stdlib.h> void remov( char str[]) { int i=0,j=0 ;

while (str[i]!='\0') { // Check for the appearance of a and c if ((str[i]=='a' && str[i+1]=='c') ) { str[i]=' ';

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

str[i]=' '; str[i+1] = ' ' ; i+=2 ;

// Check for the appearance of b else if (str[i]=='b') { str[i]=' '; i++ ;

} else {

str[j]=str[i] ; j++ ; i++ ;

} str[j]='\0'; printf ("\nThe string is %s",str) ; } int main() { char str[10] ; printf ("\nEnter the string") ; scanf ("%s",str) ; remov(str) ; return 0 ;

Reply

Karthik Venkatesw aran says: May 24, 2013 at 12:49 AM Easily understandable code.. #include<stdio.h> #include<stdlib.h> void remov( char str[]) { int i=0,j=0 ;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

while (str[i]!='\0') { // Check for the occurence of ac if ((str[i]=='a' && str[i+1]=='c') ) { str[i]=' '; str[i+1] = ' ' ; i+=2 ; } // Check for the occurence of b else if (str[i]=='b') { str[i]=' '; i++ ;

} else {

str[j]=str[i] ; j++ ; i++ ;

} str[j]='\0'; printf ("\nThe string is %s",str) ; } int main() { char str[10] ; printf ("\nEnter the string") ; scanf ("%s",str) ; remov(str) ; return 0 ;

Reply SOURADEEP DAS says: May 30, 2013 at 12:02 PM The above code w ont w ork ... try to take input : abc the output should be : "" i.e null // /* Paste your code here (You may delete these lines if not writing code) */

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

/* Paste your code here (You may delete these lines if not writing code) */ #include<stdio.h> #include<string.h> void eliminate ( char input[]) { int p=0; int i; while (input[p]!='\0') { if (input[p]=='a'&&input[p+1]=='b'&&input[p+2]=='c') { for (i=3;input[p+i]!='\0';i++) input[p+i-3]=input[p+i]; input[p+i-3]='\0'; } else if (input[p]=='a'&&input[p+1]=='c') { for (i=2;input[p+i]!='\0';i++) input[p+i-2]=input[p+i]; input[p+i-2]='\0'; } else if (input[p]=='b') { for (i=1;input[p+i]!='\0';i++) input[p+i-1]=input[p+i]; input[p+i-1]='\0';

} else { p++; }

} }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

int main() { char input[]="abcdacacdbbbabc"; char *p; //printf("Enter the string :"); //scanf("%s",input); eliminate(input);

printf ("%s",input); return 0; } Reply

vishnuvardhan.2005 says: May 23, 2013 at 7:09 PM #include <iostream> using namespace std; // supresses "b" and "ac" void supress( char * s, char * c1, char c2 ) { char * temp = s; int isfirstSet = false ; for ( ; *temp != '\0' ; temp++ ) { if ( *temp == c2 ) { // do nothing i.e, don't copy } else if ( *temp == c1[0] ) { *s++ = *temp; isfirstSet = true ; } else if ( *temp == c1[1] && isfirstSet ) { s--; isfirstSet = false ; } else { *s++ = *temp; if ( isfirstSet ) isfirstSet = false ; } }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} *s = '\0'; } int main() { char s[50]; cout << "Enter string s:" << endl; cin >> s; char c1[3]="ac"; char c2 = 'b'; supress( s, c1, c2 ); cout << s << endl; return 0; } $ ./a.exe Enter string s: ad ad $ ./a.exe Enter string s: acbac $ ./a.exe Enter string s: aaac aa $ ./a.exe Enter string s: react ret $ Reply

TANMAY DAS says: May 23, 2013 at 3:56 PM //Given a string, eliminate all b and ac //in the string, you have to replace them in-place, //and you are only allowed to iterate over the string once. //(Source Google Interview Question) public class SubStringDeletion { public static void main(String args[]) { char [] str = args[0].toCharArray(); removeBandAC(str); } // Removes b and ac. public static void removeBandAC( char [] str) { StateMachine machine = new StateMachine(); machine.currentState = STATES.INITIAL;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

for ( int index=0; index < str.length; ) { char charatPos = str[index]; if (charatPos == 'b') { //Remove b. int curPos = index; while (curPos+1 < str.length) { str[curPos] = str[++curPos]; } if (machine.currentState == STATES.HASA) { machine.currentState = STATES.INITIAL; } } else if (charatPos == 'a') { machine.currentState = STATES.HASA; index++; } else if (charatPos == 'c' && machine.currentState == STATES.HASA) { //Remove ac. int curPos = index-1; while (curPos+2 < str.length) { str[curPos] = str[curPos+2]; ++curPos; } machine.currentState = STATES.INITIAL; index--;

} }

} else { if (machine.currentState == STATES.HASA) { machine.currentState = STATES.INITIAL; } index++; }

System.out.println(str);

interface STATES { int INITIAL = 1; int HASA = 2; } class StateMachine { int currentState; } /* Paste your code here (You may delete these lines if not writing code) */ Reply

Matt says: May 22, 2013 at 3:58 PM

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Variant on state machine (C#): const int One = 1; const int Tw o = 2; static void StringFilter(string s) { int j = 0, state = One; var c = s.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] != 'b' && c[i] != 'c') { c[j++] = c[i]; state = One; } else if (c[i] == 'c' && state == Tw o) { j--; } if (c[i] == 'a' && state == One) { state = Tw o; } } s = new string(c); if (j < s.Length) { s = s.Remove(j); } Console.WriteLine(s); } Reply

praveen kum ar says: May 21, 2013 at 6:59 PM

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

void remove_B_and_AC( char *str) { int i,j; if (!str) return ; for (i=0, j=0; i < strlen (str); i++) { if (str[i] == 'b') continue ; else if (str[i] == 'c') { if ((j > 0) && (str[j-1] == 'a')) j--; else { str[j] = str[i]; j++; } } else { str[j] = str[i]; j++; } } str[j] = '\0'; } Reply

Saurav Bisw as says: May 21, 2013 at 1:56 AM /* l = len(s) i=0 j=i while (i<l): if s[j] == "b": s = s[:j] + s[j + 1:] i=i+1 elif s[j] == "a" and s[j + 1] == "c": s = s[:j] + s[j + 2:] i=i+2 else : i=i+1 j=j+1
Are you a developer? Try out the HTML to PDF API

*/

open in browser PRO version

pdfcrowd.com

Reply

kaiser says: May 20, 2013 at 4:26 PM #include #include using namespace std; int main() { char *str = new char[100]; bool flag; int new _str_idx=0,cur_str_idx=0; cout < < "Enter the String : "; cin>>str; w hile(str[cur_str_idx] != '\0'){ flag=true; if(str[cur_str_idx] == 'b'){ cur_str_idx++; flag=false; } else if(str[cur_str_idx]=='a' && str[cur_str_idx+1]=='c'){ cur_str_idx=cur_str_idx+2; flag=false; } if(flag==true){ if(str[cur_str_idx] == 'c' && str[new _str_idx-1] == 'a') new _str_idx--; else{ str[new _str_idx]=str[cur_str_idx]; new _str_idx++; } cur_str_idx++; } } str[new _str_idx]='\0'; cout << "After Modification : " << str < return EXIT_SUCCESS;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} Reply

rahul says: May 20, 2013 at 1:26 PM public class ReplaceString { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub StringBuilder stBuilder=new StringBuilder("aacacc"); StringBuilder result=new StringBuilder(); result=replaceString(stBuilder); System.out.println(result); result=replaceAllString(stBuilder); System.out.println(result); } private static StringBuilder replaceAllString(StringBuilder stBuilder) { // TODO Auto-generated method stub if(stBuilder.length()==0){ return stBuilder; } for(int i=0;i0 && character=='c' && stBuilder.charAt(i-1)=='a'){ stBuilder.delete(i-1, i+1); i=i-2; } else if(character=='b'){ stBuilder.deleteCharAt(i); i--; } } return stBuilder; } private static StringBuilder replaceString(StringBuilder stBuilder) { // TODO Auto-generated method stub if(stBuilder.length()==0){

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

return stBuilder; } boolean flag=false; boolean preFlag=false; for(int i=0;i<stBuilder.length();i++){ char character=stBuilder.charAt(i); flag=false; if(character=='a') flag=true; else if(character=='c' && preFlag){ stBuilder.delete(i-1, i+1); i=i-2; } else if(character=='b'){ stBuilder.deleteCharAt(i); i--; } preFlag=flag; } return stBuilder; } } Reply rahul says: May 20, 2013 at 1:27 PM Sorry for w rong indentation public class ReplaceString { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub StringBuilder stBuilder= new StringBuilder("aacacc"); StringBuilder result= new StringBuilder(); result=replaceString(stBuilder); System.out.println(result); result=replaceAllString(stBuilder); System.out.println(result); } private static StringBuilder replaceAllString(StringBuilder stBuilder) { // TODO Auto-generated method stub

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

// TODO Auto-generated method stub if (stBuilder.length()==0){ return stBuilder; } for ( int i=0;i<stBuilder.length();i++){ char character=stBuilder.charAt(i); if (i>0 && character=='c' && stBuilder.charAt(i-1)=='a' stBuilder. delete (i-1, i+1); i=i-2; } else if (character=='b'){ stBuilder.deleteCharAt(i); i--; } } return stBuilder;

private static StringBuilder replaceString(StringBuilder stBuilder) { // TODO Auto-generated method stub if (stBuilder.length()==0){ return stBuilder; } boolean flag= false ; boolean preFlag= false ; for ( int i=0;i<stBuilder.length();i++){ char character=stBuilder.charAt(i); flag= false ; if (character=='a') flag= true ; else if (character=='c' && preFlag){ stBuilder. delete (i-1, i+1); i=i-2; } else if (character=='b'){ stBuilder.deleteCharAt(i); i--; } preFlag=flag; } return stBuilder; } } Reply

Sivakanth says: May 20, 2013 at 1:09 PM void main()

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

void main() { char buf[10] = "bacaqbacz"; char * in_str = buf; char * out_str = buf; printf ("buf = %s\n",buf); while (*in_str != '\0') { if (*in_str == 'b') { in_str++; } else if (*in_str == 'a' && *(in_str+1) == 'c') { in_str = in_str+2; } else { *out_str++ = *in_str++; } } *(out_str) = '\0'; printf ("buf = %s\n",buf); } Reply

Ankur says: May 20, 2013 at 12:40 AM public class StringPatternRemoverOfSomeCharacters { /** * @param args */ public static void main(String[] args) { String s = "react"; StringBuilder sb = new StringBuilder(); for ( int i=0 ; i<s.length();i++){ if (s.charAt(i)=='b') continue ; if (s.charAt(i)== 'a'){ if (s.charAt(i+1)== 'c'){ i++; continue ; } } sb.append(s.charAt(i)); } System.out.println("After REmoval String left is " + sb.toString()); } } Reply

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

atul says: May 20, 2013 at 12:21 AM \ void remove_ac_b( char *str, int len) { int end=0,i; for (i=0;i<len;) { if (i+1<len && str[i]=='a' && str[i+1]=='c') { i=i+2; } else if (str[i]=='b') { i++; } else { str[end]=str[i]; end++; i++; } } if (end==0) printf ("\nAfter removing 'ac' and 'b' = \"\""); else { str[end]='\0'; printf ("\nAfter removing 'ac' and 'b' = %s",str); } printf ("\n"); } Reply

guptaabhishek849@gm ail.com says: May 20, 2013 at 12:08 AM void removebANDac( char str[]) { int i; int counter=0; for (i=0;i< strlen (str);i++) { if (str[i]=='b') continue ; else if (str[i]=='a'&& i+1< strlen (str)) { if (str[i+1]=='c') { i++;

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} else { }

i++;

str[counter]=str[i]; counter++;

} else {

} } str[counter]='\0';

str[counter]=str[i]; counter++;

Reply

Comment
Name ( Required)

Email ( Required)

Website URI

Your Com m ent (Writing code? please paste your code betw een sourcecode tags)

[sourcecode language="C"] /* Paste your code here (You may delete these lines if not writing code) */ [/sourcecode]

Notify me of follow up comments via e-mail. You can also subscribe w ithout commenting.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Type the text


Privacy & Terms

Have Your Say

@geeksforgeeks, Some rights reserved

Contact Us

Powered by WordPress & MooTools, customized by geeksforgeeks team

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Vous aimerez peut-être aussi