An example logic on counting no.of spaces and characters other than spaces in a String in Java.
The last logic (splitting into words) will be good if the string 'st' does not start/end with space, if it does then, you'll need to write other logic or simply extend this, mostly strings wont start/end up with a space. The above logic works fine, no matter where the space comes. When a string is split into words with help of a space, (in the above example) there are 4 words, so it is clear that there will be 3 words, so (words.length-1) [1 less than the no.of words].
Example
Output
Note [Last Logic]
The last logic (splitting into words) will be good if the string 'st' does not start/end with space, if it does then, you'll need to write other logic or simply extend this, mostly strings wont start/end up with a space. The above logic works fine, no matter where the space comes. When a string is split into words with help of a space, (in the above example) there are 4 words, so it is clear that there will be 3 words, so (words.length-1) [1 less than the no.of words].
No comments:
Post a Comment