aspose file tools*
The moose likes Beginning Java and the fly likes how to i replace all non-alphabetic chars with `*`in a String? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to i replace all non-alphabetic chars with `*`in a String?" Watch "how to i replace all non-alphabetic chars with `*`in a String?" New topic
Author

how to i replace all non-alphabetic chars with `*`in a String?

h thornton
Greenhorn

Joined: Jan 07, 2010
Posts: 5
Howdy!

Im currently working on a project and i need to accomplish that kind of task, not sure if i should convert between charArrays or not?

for example, i have to replace String "could you please spare a sec?" with "could*you*please*share*a*sec*"

any help is greatly welcome
Karthick Dharani Vidhya
Ranch Hand

Joined: Feb 23, 2008
Posts: 89
Hi,

You may want to check String.replaceAll() method that takes in a Regular expression as first parameter and the string to be replaced as second.




Karthick D V
h thornton
Greenhorn

Joined: Jan 07, 2010
Posts: 5
Karthick Dharani Vidhya wrote:Hi,

You may want to check String.replaceAll() method that takes in a Regular expression as first parameter and the string to be replaced as second.





Thanks alot! i really wondered far with my guesses how to accomplish this..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
If you want lots of marks as a beginner, you would do well to try a different approach. Try
  • splitting the entire String into a char array (there is a String method which does that), then
  • iterate the array (using an old-fashioned for loop) and
  • using the appropriate methods of the Character class (find an isXXX method) to find whether it is a letter or not, (or try the < > operators and see whether it is in the appropriate range).
  • Then you can replace the char in the array, and
  • pass the array to a new String constructor.

  • You will find lots more about the [^a-zA-Z] bit in the Java™ tutorials.
    Rajeev Trikha
    Ranch Hand

    Joined: Jan 29, 2010
    Posts: 85
    Watch out for the regular expression you use. Following the above answer using the expression

    testStr = testStr.replaceAll("[^\\w]","*");

    will preserve numbers as well as underscore whilst replacing everything else to '*'.


    Rajeev Trikha (SCJP 6)
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: how to i replace all non-alphabetic chars with `*`in a String?