Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2011-10-06
28
Medium Priority
?
216 Views
Last Modified: 2012-05-12
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 .


0
Comment
Question by:FranklinRaj22
  • 11
  • 9
  • 8
28 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 36925469
For something like this, i would do

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

and, yes, use looping
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36925509


Can't you use the replace method of the string

String s = "qweqw&werwer$sfs';

s = s.replace('&','E');
s= s.replace('$','A');
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36925522
>>Can't you use the replace method of the string

No - because that's inefficient for anything more than a couple of invocations
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 36925528
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36925540
If you have millions of magabyte strings - then think about efficiency - otherwise replace is fine
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36925700
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36926145
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36926171
>>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
 

Author Comment

by:FranklinRaj22
ID: 36927202
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927214
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927228
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927230
Do you mean that each special charactter should be replaced by its own letter, like you showed wwith & and $ ?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927235
If you give me the two strings (source and target) i'll show you what to do
0
 

Author Comment

by:FranklinRaj22
ID: 36927406
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927417
DO you have these characters very often or therea whole blocks that do not have any odf such characters?
0
 

Author Comment

by:FranklinRaj22
ID: 36927457
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927494
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927546
>>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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927570
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36928055

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
 

Author Comment

by:FranklinRaj22
ID: 36951054
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36951152
You need to escape special regex characters, e.g. "\\!"
0
 

Author Comment

by:FranklinRaj22
ID: 36951409
CEHJ,
the escae characetr works fro everything but no for '!'. I have tried muliple time.
! is the only symbol thats causing the issue .
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36951500
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
 

Author Comment

by:FranklinRaj22
ID: 36951509
Srry abt that it was another issue. Working on it.
0
 

Author Closing Comment

by:FranklinRaj22
ID: 36956519
The whole discuss was of a great learnin to me .Thanks Yan and CEHJ
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36956578
FranklinRaj22, can you tell me why you ignored my comments please?
0
 

Author Comment

by:FranklinRaj22
ID: 36981829
I havent ignored your commnets , I think yours were off great value  too .
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month11 days, 16 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question