Java expert help needed in generating a string in a particular format

HI experts,

I have a simple java doubt for which I need to have some expert help.

If I have a string , which contains special characters - eg; (944) 6$78-0.98 , I need to remove all the special characters and finally I need to have the number as shown - %9%4%%4%6%7%8%0%9%8% . How can I accomplish this?

Any help in this regard would be well appreciated.
Thanks,
Sree
Sreejith22Asked:
Who is Participating?
 
chaitu chaituCommented:
i think this would be fine.

      String INPUT = "(944) 6$78-0.98 ";
      
                 INPUT= INPUT.replaceAll("[^\\d]", "").replaceAll("(\\d)", "%$1");
                 System.out.println(INPUT);
0
 
käµfm³d 👽Commented:
Try this:

import java.util.regex.*;

String source = "(944) 6$78-0.98";
Pattern p = Pattern.compile("\\D");
Matcher m = p.Matcher(source);
String result = m.replaceAll("");

p = Pattern.compile("(\\d)");
m = p.Matcher(result);
result = m.replaceAll("%$1");

Open in new window

0
 
käµfm³d 👽Commented:
If you really need that % at the end of the string, then you can simply append one after all of the previously described logic runs.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
chaitu chaituCommented:
INPUT= INPUT.replaceAll("[^\\d]", "");
	           System.out.println(INPUT); 
	           System.out.println(INPUT.replaceAll("(\\d)", "%$1"));

Open in new window

0
 
Sreejith22Author Commented:
chaituu:

your output does not exclude spl characters and there is no % in the end.
0
 
Sreejith22Author Commented:
In order to add a % to the end of that string, do I need to convert it to string buffer, and back to string again?
0
 
for_yanCommented:
No you don't , just

String s = s + "%";
0
 
chaitu chaituCommented:
above code i pasted will fetch you following output.

%9%4%4%6%7%8%0%9%8
0
 
käµfm³d 👽Commented:
You can give those 30 points to chaituu. Plagiarism of that quality deserves nothing less than full credit.
0
 
Sreejith22Author Commented:
@kaufmed:

Extremely sorry from my bottom heart, if my rating was inappropriate. I beg your pardon for the same.

Thanks,
Anees
0
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.

All Courses

From novice to tech pro — start learning today.