-1

I have to count number of words in a string like (hello how? are y*ou Akanksha-Mishra?) so the answer is 4.because the word including special character is not considered and words joined by hyphen is considered to be one word. So, how can I do it.

3 Answers3

1

You can loop over each character and check their order,like A has 65 and Z has 92.You can check if the order of a character falls within a range and if they do you know that they are simple alphabets else special character.

devansh
  • 89
  • 2
  • 8
1

In case you want to code it out in Java, here's what you can do:

    public class CountSpecCharacter    
    {    
    public static void main(String[] args) {    
        String string = "hello how? are y*ou Akanksha-Mishra?";    
        int count = 0, spec = 0;
        for(int i = 0; i < string.length(); i++) {  
            if ((string.charAt(i)>64 && string.charAt(i)<=122) || string.charAt(i) == 32) 
            {    
                count++;
            }      
        }     
        spec = string.length() - count;
        System.out.println("Number of Special Characters: " + spec);    
    }    
} 

Here, I have implemented a for loop, that is being used to count the number of characters in the string, including the whitespaces. Then that number is subtracted by the total length of the string, to find out the number of special characters.

neeltron
  • 11
  • 3
  • Actually I have to count the number of words which don't have any special character in between or any numeric digits. Please help for the same @neeltron – Akanksha Mishra Jan 25 '21 at 04:15
  • In that case, you can extract the words into an array and then you can use my code to filter out the words that contain special characters. Here's how you can convert your string into an array: https://stackoverflow.com/questions/4674850/converting-a-sentence-string-to-a-string-array-of-words-in-java – neeltron Jan 25 '21 at 04:48
0

In case every special character may appear in the end of a word and it will be count (like "how?" in your example) - I would suggest something like:

    public static void main(String[] args) {
            int counter = 0;

            Pattern pattern = Pattern.compile("[a-zA-Z]+[^A-Za-z]*");
            //String string = "blah blah-blah bla*h";
            String string = "hello how? are y*ou Akanksha-Mishra?";

            string = string.replace("-","");
            String[] words = string.split(" ");
            for (String word: words) {
                Matcher matcher = pattern.matcher(word);
                if (matcher.matches()) {
                    counter++;
                }
            }
    
            System.out.println(counter);
        }
    }

Let me know if you need extra explanations.

javadev
  • 688
  • 2
  • 6
  • 17