finding number of words in a String using recursive method

count characters in string recursion in c
count characters in string recursion python
recursive function count occurrences
recursive function to do substring search java
count characters in string recursion java
find length of string using recursion python
how to count the number of occurrences of a character in a string in java
number of occurrences of a substring in a string in java

I want to count number of words in my string using recursive method (java)

so far i wrote this code

public static int CountWords(String sen) {
    int count = 0;
    int i = sen.indexOf(" ");
    if (sen.isEmpty()) {
        return 0;
    }else 
        if (i == sen.indexOf(" ")) {
      return count++;
   }
  //sen.substring(0,sen.indexOf(" ")-1);
    count++;
    return count + CountWords(sen.substring(i + 1));
}

i always get 0 when i call the method can anyone help me make this code run

How you're using indexOf is the problem. You're setting i to the result of calling indexOf, then seeing if it's equal to the result of calling indexOf on the same string with the same parameter. The result of the test i == sen.indexOf(" ") will always be true. That's why you always get 0.

String#indexOf returns -1 if the char it's looking for is not found. indexOf comes in very handy here.

Also you shouldn't need a local count variable. Introducing a variable here just makes the code harder to read, because the reader has to hunt around to figure out what the value of it is.

Assuming your input always has exactly one blank between words this could be done as:

public static int countWords(String s) {
    if (s.isEmpty()) return 0;
    if (s.indexOf(" ") == -1) return 1;
    return 1 + countWords(s.substring(s.indexOf(" ") + 1));
}

For multiple blanks between words you can check for a blank and skip past it:

public static int countWords(String s) {
    if (s.isEmpty()) return 0;
    if (s.indexOf(' ') == -1) return 1;
    if (s.charAt(0) == ' ') return countWords(s.substring(1));
    return 1 + countWords(s.substring(s.indexOf(' ') + 1));
}

Count occurrences of a substring recursively, How you're using indexOf is the problem. You're setting i to the result of calling indexOf , then seeing if it's equal to the result of calling indexOf on the same  Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string. 1. Iterative 2. Recursive. Examples: Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7

This should work, I think:

public static int countWords(String sen) {
    int i = sen.indexOf(" ");
    if (sen.isEmpty()) {
        return 0;
    } else if (i == -1) {
        return 1;
    } else return 1 + countWords(sen.substring(i + 1));
}

Some notes on what is happening:

  1. Java naming conventions dictate you should start method names with a lower case letter
  2. The line if (i == sen.indexOf(" ")) is redunant - you just assigned i to be that before, so it'll always evaluate to true.
  3. And therefore, your recursion never gets called. You need to change it so that if sen isn't empty and contains at least one more space, countWords calls itself with sen minus the first word.

Program for length of a string using recursion, Given two strings str1 and str2, the task is to count the number of times “str2” occurs in Now, talking about the recursive case, compare first substring of str1 with str2 and Driver function. int main(). {. string str1 = "geeksforgeeks" , str2 = "​geeks" ; Count occurrences of a word in string · Count of occurrences of a "1(0​+)1"  Anyway, I've made a method which counts the words using booleans, a while loop and a counter. However I need to some how shape this into a recursive method that counts the amount of words in a string, a word is delimited by one or many spaces. countWords(" hello this is an example", 0); // returns 5

This method uses a String with no spaces as a base case. Then it removes everything up to and including the first space in the String and recurses.

It handles both the special case of an empty String and the case that a String passed to the method starts with a space appropriately.

public static int CountWords(String sen) 
{   int i = sen.indexOf(" ");
    if(sen.isEmpty()) return 0;          // special case
    if(i == -1) return 1; // base case

    if(i != 0)
        return 1 + CountWords(sen.substring(i+1));
    else
        return CountWords(sen.substring(1));
}

How to Count Number of Words in String - Java , string using recursion. Given a string calculate length of the string using recursion. We have discussed 5 Different methods to find length of a string in C​++ · How to find private static int recLen(String str) Length Of Last Word in a String  Re: Using recursion to find the number of occurences of a character in a string Then check to see if the first character of the string is the passed in character. If so, return one plus the results of the freq() with the first character removed from the string.

This will work -

public static int CountWords(String sen) {
    if("".equals(sen)){
        return 0;
    }
    int count = 0;
    int i = sen.indexOf(" ");
    String substr = sen.substring(0,i+1) ;
    if (i != -1) {
        count++;
    }else{
        if(sen.length()>0){
            count++;
        }
        sen="";
    }
    //sen.substring(0,sen.indexOf(" ")-1);
    return count + CountWords(sen.substring(substr.length()));

}

3 ways to Count words in Java String, We will see two examples to find number of words in Java String, first one This method return word count without using regular expression */ public (Solution); Write a Program to calculate factorial using recursion in Java? Recursive function to check if a string is palindrome. Given a string, write a recursive function that check if the given string is palindrome, else not palindrome. Examples : Input : malayalam Output : Yes Reverse of malayalam is also malayalam. Input : max Output : No Reverse of max is not max. We have discussed an iterative function here.

Java reverse string using recursion, In this solution, we will use the split() method of java.lang.String class to count the number of words in a given sentence. This solution uses the regular expression "​  Enter any number: 23456 After reverse the no is :65432 Reversing a number using While loop. In the above program we learnt how to reverse a number using recursive function. Here we would learn how to do it using while loop.

C Program Count Number Of Words In A String, In this post, we will see a Java program to reverse a string using recursion. Read More: Reverse words in a string in Java To reverse a string by characters​, we can write a recursive function which will Find me on Facebook and Twitter. Convert String to int · Convert int to String · Convert String to long · Convert long  First program reverses the given string using recursion and the second program reads the string entered by user and then reverses it. To understand these programs you should have the knowledge of following core java concepts: 1) substring() in java. 2) charAt() method.

Recursion Examples, Using Standard Method; Using Function; Using Recursion; Using Pointers and While Loop. A string is nothing but an array of characters. The value of a string is​  In this article, you will learn to create recursive function; a function that calls itself. Also, you will learn about its advantages and disadvantages. A method that calls itself is known as a recursive method. And, this technique is known as recursion. A physical world example would be to place two parallel mirrors facing each other.

Comments
  • If you send in the String, "The cow jumped over the moon \\" then you get 7 as the count. OP should consider improving the algorithm to detect this.
  • Also probably need a defensive check if the String is null.
  • @staticx: that is good advice, but i felt like i needed to leave something for the OP. It looked like the core problem was not getting recursion, so that was the scope of my answer.
  • No problem, your response is greatly appreciated.
  • Actually looking at the OP's code now, i think the problem was just not getting the termination condition right.
  • There's no point getting the indexOf(" ") if sen is empty. If you move that check down to countWords recursive call, then you essentially get @NathanHughes' answer.
  • Also probably need a defensive check if the String is null.
  • @staticx True. I had adapted the OP's code and that must have slipped by. On an empty string, the performance hit should be negligible, but you are right, it's not as pretty as it could be.
  • Not sure I agree on the defensive null check. I'm not a fan of defensively null checking excessively if there is no clearly appropriate value. I guess it depends on the definition of how many words a null string has: 0, or is it an error to ask.
  • If you call isEmpty on a null String, you get a NullPointerException.
  • Please don't post answers to ask others to review your code.