File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
h thornton
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



 
h thornton
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47292
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 85
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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 '*'.
     
    I agree. Here's the link: http://aspose.com/file-tools
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic