vineri, 19 februarie 2010

How to remove vowels from a string

It seems that's easy in Java 5 using regex. Have a look on this code:
Pretty straightforward.

public class NoVowels
{
public String replaceVowels(String source)
{
String result="";
String regex="[AEIOU]";
String replacement="";
result=source.toUpperCase().replaceAll(regex,replacement);
return result;
}

public static void main(String[] args)
{
String test = "Abracadabra";
String result = "";
NoVowels nw = new NoVowels();
result = nw.replaceVowels(test);

System.out.println("test string="+test);
System.out.println("result string="+result);
}
}

And we obtain:
test string=Abracadabra
result string=BRCDBR

Now I'll try same thing in Clojure.
I have found and installed clojure box.
I go on my windows xp in start->programs->clojure box->clojure box link.

In the repl I type:

(require '(clojure.contrib [str-utils2 :as s]))

I did this to select the namespace for this replace function which in this example is s. Then I write the replace code.

(s/replace (s/upper-case "Abracadabra") #"[AEIOU]" "")

And I get:
"BRCDBR"

Two lines of code !


Niciun comentariu:

Trimiteți un comentariu