Replace set of characters with another set of characters in a string .

I have set of special characters that will not be accepted by my system , so I am palnnin to replace each with a equivalent character so that wen i send them back i can recover the original symbols . Do we have any classes in java that can help me or will I have to iterate the whole string to find and replace ? Replace or pattern classes do not help me .
eg
$  replaced wit E
& reaplced  wit A
I have a lot more like this , so i should be able to detect the strings that have these special charater and replace that character with an equivalent . So any classes methods should help, or ill go the round way of loopin and searchin each and everycharacter .


FranklinRaj22Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
For something like this, i would do

final String SOURCE = "$&";
final String REPLACE = "EA";

and, yes, use looping
0
for_yanCommented:


Can't you use the replace method of the string

String s = "qweqw&werwer$sfs';

s = s.replace('&','E');
s= s.replace('$','A');
0
CEHJCommented:
>>Can't you use the replace method of the string

No - because that's inefficient for anything more than a couple of invocations
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

for_yanCommented:
This is how it is tested:
        String s15 = "qweqw&werwer$sfs";

s15 = s15.replace('&','E');
s15= s15.replace('$','A'); 

        System.out.println(s15);

Open in new window

Ouput
qweqwEwerwerAsfs

Open in new window

0
for_yanCommented:
If you have millions of magabyte strings - then think about efficiency - otherwise replace is fine
0
CEHJCommented:
It's not efficient in human terms, nor is it very extensible/reusable, hence it's just bad programming. FranklinRaj22, let me know if you don't know how to implement it
0
for_yanCommented:
Unless this replace is the main stuff that you application is doing all the time with tons of strings, this will make no difference.
In all other cases the time it takes to open the file will be on orders of magnitude bigger than  string replacement.
And why it is less reusable than anything else?

Don't know what is "bad programming". Good programming is when it works.
0
CEHJCommented:
>>Don't know what is "bad programming". Good programming is when it works.

The fact that you think that is probably at the root of why it's not good programming
0
FranklinRaj22Author Commented:
i hav around 20 special characters that needs a replacement , and I will hav to check aroung 5000000 lak string for these characters and replace them every 5 mins.

If i could find using pattern class or sme string operation in java and find out if teh word had a special character or not then it will reduce my effort of replacing it more effective . thats y using 'replace' was a question . But if there are no other options then will hav to do it . Please advice
0
for_yanCommented:
No guarantee that pattern will work faster than replace, but specify waht are the characters and we can come up with regex for it
0
CEHJCommented:
I would user the approach i outlined. If i were doing this myself, i would store both strings (as i gave examples of) in external files
0
for_yanCommented:
Do you mean that each special charactter should be replaced by its own letter, like you showed wwith & and $ ?
0
CEHJCommented:
If you give me the two strings (source and target) i'll show you what to do
0
FranklinRaj22Author Commented:
Yan u r right , each character will have to be replaced by its equivalent character .
20 special character will be replaced by 20 other characters .

CEHJ its not a string or regex , its a character set that will be replaced by another character set .
0
for_yanCommented:
DO you have these characters very often or therea whole blocks that do not have any odf such characters?
0
FranklinRaj22Author Commented:
i get a fed of 5000000 Strings, among these a a few say 10 - 20 % might have these characters .
These strings can hav one or more of these special characters , and not nessary that they should follow any pattern . The can or cannot be consective characters .
 
0
for_yanCommented:
I think you can use first regex to filter ut those which do not have at all these characres
and then for thiose l;eft - you firts can determine which of the 20 are present in each
and then do replace() for those which are lest in this particular string
0
CEHJCommented:
>>its a character set that will be replaced by another character set .

I'm aware of that. See below for the most efficient way to do it. As i said, it would be stronger to get what you call 'character sets' from files:


public class Replacer {
    public static void main(String[] args) {
	System.out.println(Replacer.replace("aeiou", "zyxwv", "The quick brown fox jumps over the lazy dog"));
    }

    public static String replace(String find, String replace, String data) {
	String result = null;
	int index = -1;
	StringBuilder sb = new StringBuilder(data);
	for(int i = 0;i < sb.length();i++) {	
	    char c = sb.charAt(i);
	    if((index = find.indexOf(c)) > -1) {
		sb.setCharAt(i, replace.charAt(index));
	    }
	}
	result = sb.toString();
	return result;
    }
}

Open in new window

0
for_yanCommented:
CEHJ suggestion is nevertheless replacenemnt - yes if you have many srings use StringBuffer -that makes sense,
but if you have charcaters not in every string, and even in less than half of strings  the main thing is to analyze beforehand
which do have and which do not have your charcters - that's where you can really get some saving in time
0
for_yanCommented:

This is how it will work still with regex:
(you should be only careful creating the pattern
to make sure you distinguish between sepeal characters in regex sense or not special
chracters)

At least this example seems to work (see output below)
I'd suggest to start with something like that -if it is really slow for you then
maybe you could try to brainstorm it.

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanStrings {



 


    public static String [] getUpdatedStrings(String [] arr, String s, HashMap<String,String>mm) {
             StringBuffer sb = new StringBuffer();
       Matcher m;
          Pattern p = Pattern.compile(s);
        for(int j=0; j<arr.length; j++){
      m = p.matcher(arr[j]);


            if (!arr[j].matches(".*"+s+".*")) continue;
          sb.delete(0,sb.length());

 while (m.find()) {
     m.appendReplacement(sb, mm.get(m.group(0)) );
 }
 m.appendTail(sb);
         arr[j] = sb.toString();


        }



        return arr;
    }

    public static void main(String[] args) {

        String reg = "[\\$&\\^\\]]";

 
        HashMap<String,String> mm = new HashMap<String,String>();
        mm.put("$","E");
        mm.put("&","A");
        mm.put("^","C");
        mm.put("]","D");

        String [] arr = {"asdasda$asdasda&fasdfsdsd","etertertert","erterter^&ertert]erte","sdfsd]]sdfsd6sdfsdfssd7asdas$","gdfgd888dasdas666asdasd"};

        arr =  getUpdatedStrings(arr,  reg, mm);

        for (String s : arr){
            System.out.println(s);
        }






 }

}

Open in new window


Output:
asdasdaEasdasdaAfasdfsdsd
etertertert
erterterCAertertDerte
sdfsdDDsdfsd6sdfsdfssd7asdasE
gdfgd888dasdas666asdasd

Open in new window

0
FranklinRaj22Author Commented:
CEHJ,
Thank you very much .
Yan,
Thanks for the update,  can '!' be used in the regex ?
because i don see anywhere they hav used it and I get a n error tryin to use it .
0
CEHJCommented:
You need to escape special regex characters, e.g. "\\!"
0
FranklinRaj22Author Commented:
CEHJ,
the escae characetr works fro everything but no for '!'. I have tried muliple time.
! is the only symbol thats causing the issue .
0
for_yanCommented:
That' how it works with eexclamations pioint:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanStrings {






    public static String [] getUpdatedStrings(String [] arr, String s, HashMap<String,String>mm) {
             StringBuffer sb = new StringBuffer();
       Matcher m;
          Pattern p = Pattern.compile(s);
        for(int j=0; j<arr.length; j++){
      m = p.matcher(arr[j]);


            if (!arr[j].matches(".*"+s+".*")) continue;
          sb.delete(0,sb.length());

 while (m.find()) {
     m.appendReplacement(sb, mm.get(m.group(0)) );
 }
 m.appendTail(sb);
         arr[j] = sb.toString();


        }



        return arr;
    }

    public static void main(String[] args) {

        String reg = "[\\!\\$&\\^\\]]";


        HashMap<String,String> mm = new HashMap<String,String>();
        mm.put("$","E");
        mm.put("&","A");
        mm.put("^","C");
        mm.put("]","D");
          mm.put("!","U");

        String [] arr = {"asdasda$as!asda&fasdfsdsd","etertertert","erterter^&ertert]erte","sdfsd]]sdfsd6s!dfsdfssd7asdas$","gdfgd888dasdas666asdasd"};

        arr =  getUpdatedStrings(arr,  reg, mm);

        for (String s : arr){
            System.out.println(s);
        }






 }

}

Open in new window


Output:
asdasdaEasUasdaAfasdfsdsd
etertertert
erterterCAertertDerte
sdfsdDDsdfsd6sUdfsdfssd7asdasE
gdfgd888dasdas666asdasd

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
FranklinRaj22Author Commented:
Srry abt that it was another issue. Working on it.
0
FranklinRaj22Author Commented:
The whole discuss was of a great learnin to me .Thanks Yan and CEHJ
0
CEHJCommented:
FranklinRaj22, can you tell me why you ignored my comments please?
0
FranklinRaj22Author Commented:
I havent ignored your commnets , I think yours were off great value  too .
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.