Results 1 to 14 of 14
  1. #1
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default No of a specific char in a string

    Hi All

    I am trying to count the number of occurrences of ',' [commas] in my string.

    For e.g.

    String s = "343,gg,6,";
    In this string the char , occurs 3 times.


    Whats the best way of doing it?

    many thanks in advance :)

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    I'r recommend going through Strings API. I'm sure you'll find everything you need for this task there.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  3. #3
    Cruncher is offline Member
    Join Date
    Mar 2010
    Posts
    88
    Rep Power
    0

    Default

    you'll want to look through and use index of,

    something like this.

    I wrote this in a few seconds, there migh tbe a slightly shorter way, you could also split it using "," as your splitter, then get the length of the array it returns. Both work i guess.

    Java Code:
    String lookIn = "fsda,fsda,fa,,,";
            String lookFor = ",";
            int count = 0;
            int a = lookIn.indexOf (lookFor, 0);
            while (a != -1)
            {
                count++;
                a = lookIn.indexOf (lookFor, a + 1);
            }
            System.out.println ("" + count);

  4. #4
    Cruncher is offline Member
    Join Date
    Mar 2010
    Posts
    88
    Rep Power
    0

    Default

    note if you use the split method if there is nothing between the split it won't count them,

    like if you have ,,, it will count it as 1. so my example above is probably the best bet

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Cruncher View Post
    note if you use the split method if there is nothing between the split it won't count them,

    like if you have ,,, it will count it as 1. so my example above is probably the best bet
    There's also the two argument split( ... ) method that does what you want, but I agree, indexOf( ... ) is much cheaper (it doesn't create all those objects). I'd do it like this:

    Java Code:
    int count= 0;
    for (int i= -1; ((i= theString.indexOf(theChar, i+1) != -1; count++);
    return count;
    All we have to do now is wait for the others to protest against my (ab)use of a for loop ;-)

    kind regards,

    Jos

  6. #6
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by JosAH View Post
    There's also the two argument split( ... ) method that does what you want, but I agree, indexOf( ... ) is much cheaper (it doesn't create all those objects). I'd do it like this:

    Java Code:
    int count= 0;
    for (int i= -1; ((i= theString.indexOf(theChar, i+1) != -1; count++);
    return count;
    All we have to do now is wait for the others to protest against my (ab)use of a for loop ;-)
    No, just your parenthesis placement.
    Java Code:
    		for (int i = -1; (i = theString.indexOf(theChar, i + 1)) != -1; count++);
    I find this more readable, and my time trials seem to indicate it's just as efficient:
    Java Code:
    	private int getCharCount(String theString, char theChar) {
    		int count = 0;
    		for (int i = 0; i < theString.length(); i++) {
    			if (theString.charAt(i) == theChar) count++;
    		}
    		return count;
    	}
    -Gary-

  7. #7
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Interestingly, if theString is really big (10,000 chars) then this is even more efficient:
    Java Code:
    	private int getCharCount(String theString, char theChar) {
    		int count = 0;
    		for (char c : theString.toCharArray()) {
    			if (c == theChar) count++;
    		}
    		return count;
    	}
    Both of the other methods are better for short (100-char) Strings. I'll post my test code if anybody's interested.

    -Gary-

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by gcalvin View Post
    No, just your parenthesis placement.
    Yep, they were dead wrong, sorry about that, I didn't test it. Being on old C/C++ programmer that idiom is burned in my fingers and I don't care for verbosity.

    kind regards,

    Jos

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by gcalvin View Post
    Interestingly, if theString is really big (10,000 chars) then this is even more efficient:
    The code iterates over an array with no method calls involved. The number of commas in the String can also be a factor (try all commas in a String versus no (or a few) commas in it).

    kind regards,

    Jos

  10. #10
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default

    Quote Originally Posted by gcalvin View Post

    I'll post my test code if anybody's interested.

    -Gary-
    test code please,
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  11. #11
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by sonny View Post
    test code please,
    Here it is:
    Java Code:
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Random;
    
    public class CharacterCountTest {
    	private static final int TRIALS_PER_RUN = 10;
    	private Random rnd = new Random();
    
    	public void run(int samples, int charCount, double frequency) {
    		// generate test data
    		String[] testData = new String[samples];
    		for (int i = 0; i < samples; i++) {
    			testData[i] = generateTestString(charCount, frequency);
    		}
    		NumberFormat nf = new DecimalFormat("0000");
    
    		// time trial method A
    		long millis = System.currentTimeMillis();
    		for (int i = 0; i < samples; i++) {
    			int count = getCharCountA(testData[i], ',');
    		}
    		System.out.print("    ");
    		System.out.print(nf.format(System.currentTimeMillis() - millis) + "      ");
    
    		// time trial method B
    		millis = System.currentTimeMillis();
    		for (int i = 0; i < samples; i++) {
    			int count = getCharCountB(testData[i], ',');
    		}
    		System.out.print(nf.format(System.currentTimeMillis() - millis) + "      ");
    
    		// time trial method C
    		millis = System.currentTimeMillis();
    		for (int i = 0; i < samples; i++) {
    			int count = getCharCountC(testData[i], ',');
    		}
    		System.out.print(nf.format(System.currentTimeMillis() - millis) + "      ");
    		System.out.println();
    
    	}
    
    	private int getCharCountA(String theString, char theChar) {
    		int count = 0;
    		for (int i = -1; (i = theString.indexOf(theChar, i + 1)) != -1; count++);
    		return count;
    	}
    
    	private int getCharCountB(String theString, char theChar) {
    		int count = 0;
    		for (char c : theString.toCharArray()) {
    			if (c == theChar) count++;
    		}
    		return count;
    	}
    
    	private int getCharCountC(String theString, char theChar) {
    		int count = 0;
    		for (int i = 0; i < theString.length(); i++) {
    			if (theString.charAt(i) == theChar) count++;
    		}
    		return count;
    	}
    
    	private String generateTestString(int charCount, double frequency) {
    		char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    				'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    		StringBuilder sb = new StringBuilder();
    		for (int i = 0; i < charCount; i++) {
    			// frequency should be a fractional value between 0 and 1, indicating
    			// how many "needles" to seed our "haystack" with. .001 is very few
    			// needles, and .999 is practically all needles and no hay
    
    			if (rnd.nextDouble() > frequency) {
    				sb.append(alphabet[rnd.nextInt(26)]);
    			} else {
    				sb.append(',');
    			}
    		}
    		return sb.toString();
    	}
    
    	public static void main(String[] args) {
    		CharacterCountTest cct = new CharacterCountTest();
    		System.out.println("Very short strings, lots of needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(1000000, 10, 0.8);
    		}
    
    		System.out.println("Very short strings, few needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(1000000, 10, 0.2);
    		}
    
    		System.out.println("Short strings, lots of needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(100000, 100, 0.8);
    		}
    
    		System.out.println("Short strings, few needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(100000, 100, 0.2);
    		}
    
    		System.out.println("Longer strings, lots of needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(10000, 1000, 0.8);
    		}
    
    		System.out.println("Longer strings, few needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(10000, 1000, 0.2);
    		}
    
    		System.out.println("Really long strings, lots of needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(1000, 10000, 0.8);
    		}
    
    		System.out.println("Really long strings, few needles");
    		System.out.println("Method A  Method B  Method C");
    		for (int i = 0; i < TRIALS_PER_RUN; i++) {
    			cct.run(1000, 10000, 0.2);
    		}
    
    	}
    }
    And my results:
    Java Code:
    Very short strings, lots of needles
    Method A  Method B  Method C
        0123      0106      0051      
        0117      0082      0043      
        0114      0079      0040      
        0114      0077      0039      
        0120      0078      0040      
        0114      0076      0039      
        0114      0076      0040      
        0113      0080      0036      
        0115      0077      0038      
        0114      0077      0038      
    Very short strings, few needles
    Method A  Method B  Method C
        0103      0091      0041      
        0089      0111      0057      
        0088      0078      0079      
        0086      0093      0048      
        0085      0093      0053      
        0086      0091      0046      
        0085      0098      0050      
        0085      0093      0046      
        0085      0091      0053      
        0085      0077      0038      
    Short strings, lots of needles
    Method A  Method B  Method C
        0094      0045      0025      
        0093      0047      0025      
        0094      0047      0025      
        0092      0035      0025      
        0092      0037      0025      
        0092      0037      0024      
        0093      0039      0025      
        0092      0038      0024      
        0092      0041      0024      
        0120      0061      0027      
    Short strings, few needles
    Method A  Method B  Method C
        0055      0048      0029      
        0054      0035      0027      
        0053      0037      0025      
        0054      0040      0025      
        0054      0037      0024      
        0054      0038      0024      
        0056      0040      0025      
        0054      0041      0024      
        0055      0047      0025      
        0055      0047      0025      
    Longer strings, lots of needles
    Method A  Method B  Method C
        0089      0032      0022      
        0089      0033      0021      
        0090      0033      0021      
        0089      0034      0021      
        0089      0035      0021      
        0089      0038      0023      
        0089      0032      0022      
        0089      0033      0021      
        0090      0033      0022      
        0089      0037      0022      
    Longer strings, few needles
    Method A  Method B  Method C
        0049      0035      0021      
        0049      0035      0021      
        0050      0038      0022      
        0049      0032      0021      
        0049      0032      0022      
        0048      0033      0021      
        0048      0034      0022      
        0049      0035      0022      
        0049      0035      0021      
        0049      0039      0022      
    Really long strings, lots of needles
    Method A  Method B  Method C
        0088      0035      0021      
        0089      0032      0021      
        0089      0034      0021      
        0090      0031      0020      
        0089      0037      0021      
        0089      0033      0021      
        0088      0032      0021      
        0089      0034      0021      
        0088      0033      0021      
        0089      0034      0020      
    Really long strings, few needles
    Method A  Method B  Method C
        0048      0034      0021      
        0048      0032      0021      
        0048      0035      0021      
        0048      0032      0021      
        0048      0036      0021      
        0048      0033      0021      
        0048      0037      0020      
        0048      0034      0020      
        0048      0032      0021      
        0048      0034      0022
    -Gary-
    Last edited by gcalvin; 05-26-2010 at 09:04 PM.

  12. #12
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    If you turn the frequency parameter even lower (like to 0.01), that's when JosAH's method starts to shine. In retrospect, 0.2 is not a great value to test with -- it's still 20% of all characters.

    -Gary-
    Last edited by gcalvin; 05-26-2010 at 08:56 PM.

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by gcalvin View Post
    If you turn the frequency parameter even lower (like to 0.01), that's when JosAH's method starts to shine. In retrospect, 0.2 is not a great value to test with -- it's still 20% of all characters.

    -Gary-
    What surprises me is that all methods get a bit faster with the longer Strings. I took the liberty to copy and paste your program source and I'll play a bit with it when I find the time.

    kind regards,

    Jos

  14. #14
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    That might be due to VM optimizations. It could be more informative to put the main method code in a method and call that method say five times then compare the results.

Similar Threads

  1. How can i insert a char into a string
    By Jamie in forum New To Java
    Replies: 8
    Last Post: 02-17-2011, 08:59 PM
  2. Char to Bit String
    By Krooger in forum New To Java
    Replies: 2
    Last Post: 01-29-2010, 02:26 AM
  3. Convert Char To String
    By fh84 in forum New To Java
    Replies: 15
    Last Post: 10-28-2009, 09:59 PM
  4. char to string
    By kian_hong2000 in forum New To Java
    Replies: 2
    Last Post: 08-25-2008, 01:51 PM
  5. Help with, String, Char
    By lenny in forum New To Java
    Replies: 1
    Last Post: 07-25-2007, 02:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •