Link to home
Start Free TrialLog in
Avatar of mr_usmannaeem
mr_usmannaeem

asked on

Replace Substings with Substrings

With the following code below I can replace all the A's with T1.
But I am not sure how to replace B with T2 C with T3 at the same time.

String Text="AACB";
String output="";

String patternStrA = "A";
String replacementStrA = "T1";
   
// Compile regular expression
Pattern patternA = Pattern.compile(patternStrA);

// Replace all occurrences of pattern in input
Matcher matcherA = patternA.matcher(Text);

output = matcherA.replaceAll(replacementStrA);
 System.out.println(output);
Avatar of keyurkarnik
keyurkarnik

First - Do not  use pattern-matcher for this - they are expensive to use if you are not going to compile and keep them for future use. Here you need to check it once or twice at max, and you will need to create 26 or 52 matchers depending on the english alphabet and case sensitive behaviour.

You can do this as follows :

1. Parse the string characterwisein a for loop
2. Take every character, and get its ascii value
3. Subtract the ascii value from the ascii value of 'A'
4. Take the result and add 1 to it.
5. Now append the result to 'T', and append the resulting string to a new string (sue StringBuffer)

At the end of the loop you would have the full new string


Experts - please do not post any code here
Avatar of mr_usmannaeem

ASKER

sample code would be helpful....please
tell you what -
write in some code according to the algo - i will hep modify it :)
String Text="AACB";
String output="";

for(int i=0;i<Text.length();i++){
StringBuilder buf = new StringBuilder();

char temp=Text.charAt(i);
      
// I dont get how to the ascii part, but understood the structure of your algo
      
   buf.append(temp);
   output=buf.toString();
}
System.out.println(output);

Thanks for your help
ASKER CERTIFIED SOLUTION
Avatar of keyurkarnik
keyurkarnik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial