- my webspace

- my webspace

Latest Comment

Why I must believe in GOD
Testing time is almost passed..there are many colours in lif...
27/06/12 01:43 More...
By Tarun Shekhawat

Allama Iqbal - Selective verse...
Really good work about this website was done. Keep trying mo...
07/03/10 15:04 More...
By Roderick

Allama Iqbal - Selective verse...
Great Job
You have dont a great job of collecting these... Even I had ...
25/08/09 01:01 More...
By Sikandar

O ye who don't believe !
It's like Lehman Brothers :grin
11/10/08 10:31 More...
By anurag Chaturvedi

I Protest
Thanks Sikku for the feedback. I never intend to blame, a...
29/07/08 11:06 More...
By Aminur Rashid


Lost Password?
Home arrow Java arrow Java Empty String
Java Empty String PDF Print E-mail
User Rating: / 0
Written by Aminur Rashid   
Sunday, 25 March 2012

Post JDK 1.6, the new utility in String class reads as isEmpty(). If String is empty, can it contains(CharSequence ch) another String.

Answer is YES.

static void emptyContainer(String s1, String s2) {
   if (s1.isEmpty()) {
      assert !(s1.contains(s2));

Now that made me revisit the code to find number of occurrence of a sub String inside a parent String. At a considerable amount of forums, the code variant as follows :
    public static int countSubstringV1(String mainString, String subStr) {
        int lastIndex = 0;
        int count = 0;
        while ((lastIndex = mainString.indexOf(subStr, lastIndex)) != -1) {
            lastIndex += subStr.length();


public static int countSubstringV2(String mainString, String subStr){
		int ans = 0;
		Matcher m = Pattern.compile(Pattern.quote(subStr)).matcher(mainString);
		while (m.find())
			ans++;//count it
		return ans;
More variations at rosettacode. Try the two methods above passing "Aminur","" as two arguments. First one goes in an endless loop while second one returns mainSting.length()+1.

So its better idea, to check for empty String as well, along with its null check. Specially when conditions require dependency on contains() or e.g indexOf(...).

BTW, if you are going to provide a check in countSubstring method above e.g if(subStr.isEmpty()){..} what will be your return value? 0?mainString.length()?IllegalArgumentException?

StumbleUponDigg This!Bookmark on Delicious

Add as favourites (427) | Quote this article on your site | Views: 2035 | E-mail

Be first to comment this article
RSS comments

Only registered users can write comments.
Please login or register.

Last Updated ( Sunday, 25 March 2012 )
< Prev   Next >
Aminur Rashid