exchange a symbol

we want to replace every ',' with '/' from '(' to ' ) ' in a string called A which user enters


1
2
3
4
5
6
7
 for( int i=0; i<A.length();i++)
{
	if ( A[i]=='(')
	for(int j=0; A[j]!=')' ; j++)
		{ 
		replace(A.begin(),A.end(),',','/');
          }

i INCLUDED Algorithm Library
Here is one way to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>

using namespace std;

int main () 
{
  string input = "abd,fdsf(ab,cd,ef)shf,dhsf";
  bool inBraces = false;

  for (int i = 0; i < input.length (); i++)
  {
    char ch = input.at (i);
    if (ch == '(')
    {
      inBraces = true;
    }
    else if (ch == ',')
    {
      if (inBraces)
      {
        input[i] = '/';
      }
    }
    else if (ch == ')')
    {
      inBraces = false;
    }
  }
  cout << "Output: " << input << "\n\n";
  system ("pause");
  return 0;
 
}
the most simple way to do this is to find the indexes of '(' and ')' in a for loop and store them each in a variable. Then iterate between index A and index B and if a character is ',' just change it to '/'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<string>

using namespace std;

int main(){
string input;
cin>>input;
int start;
int finish;
for (int i=0; i<input.size(); i++){
    if (input[i]=='('){
            start = i;
        }
    else if (input[i]==')'){
        finish = i;
    }
}
for (int j=start+1; j<finish; j++){
    if (input[j]==',') { input[j] = '/'; }
}
cout<<input;
}


I suggest you follow Thomas1965 method though, since it's almost 2 times faster.
Last edited on
Topic archived. No new replies allowed.