Results 1 to 3 of 3
  1. #1
    nikki101 is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default Counting number of occurrence of substring in a string

    private static void Counting(String something, String character)
    {
    int numberOfKeys = 0;
    for (int i = 0; i < something.length(); i++)
    {
    String[] theStringArray = new String[] {theString};
    if (theStringArray[i] == character)
    numberOfKeys++;
    }
    System.out.println("\n# " + character + "s: " + numberOfKeys);
    }
    }

    I think the error runs in comparing somethingArray with character since I keep getting o for the number of occurrences. How would I solve this issue?
    Last edited by nikki101; 05-18-2013 at 04:27 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Counting number of occurrence of substring in a string

    First, you don't want to create a String array. Even if you did, it is inside the loop which would be wrong. Check out both charAt() and substring() methods of the String class and see if that helps.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    nikki101 is offline Member
    Join Date
    May 2013
    Posts
    4
    Rep Power
    0

    Default Re: Counting number of occurrence of substring in a string

    Thanks! I got it to work.

Similar Threads

  1. Replies: 13
    Last Post: 02-24-2013, 01:04 PM
  2. Replies: 1
    Last Post: 10-24-2012, 12:21 PM
  3. Replies: 9
    Last Post: 09-03-2012, 09:15 AM
  4. Replies: 14
    Last Post: 09-12-2011, 11:54 PM
  5. Counting number of entries in a file
    By lenny0 in forum New To Java
    Replies: 3
    Last Post: 05-10-2011, 03:40 AM

Posting Permissions

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