Counting Words in String

Counting words in string

Use square brackets, not parentheses:

str[i] === " "

Or charAt:

str.charAt(i) === " "

You could also do it with .split():

return str.split(' ').length;

Count the number of all words in a string

You can use strsplit and sapply functions

sapply(strsplit(str1, " "), length)

Counting words in a string - c programming

You needed

int words(const char sentence[])
{
}

(note braces).

For loops go with ; instead of ,.


Without any disclaimer, here's what I'd have written:

See it live http://ideone.com/uNgPL

#include <string.h>
#include <stdio.h>

int words(const char sentence[ ])
{
int counted = 0; // result

// state:
const char* it = sentence;
int inword = 0;

do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r': // TODO others?
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);

return counted;
}

int main(int argc, const char *argv[])
{
printf("%d\n", words(""));
printf("%d\n", words("\t"));
printf("%d\n", words(" a castle "));
printf("%d\n", words("my world is a castle"));
}

Counting words in a string

Your function can be reduced to this:

int countWords(std::string x) {

int Num = 0;
char prev = ' ';

for(unsigned int i = 0; i < x.size(); i++) {

if(x[i] != ' ' && prev == ' ') Num++;

prev = x[i];
}
return Num;
}

Here is a demo

Edit: To follow up comment:

Here is a simple way to replace other characters with ' ', thought there might be a build method for this:

void replace(std::string &s, char replacer, std::set<char> &replacies)
{
for (int i=0; i < s.size(); i++)
if (replacies.count(s[i])) s[i] = replacer;

}

demo

Count words in a string method?

public static int countWords(String s){

int wordCount = 0;

boolean word = false;
int endOfLine = s.length() - 1;

for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}

How to find the count of a word in a string

If you want to find the count of an individual word, just use count:

input_string.count("Hello")

Use collections.Counter and split() to tally up all the words:

from collections import Counter

words = input_string.split()
wordCount = Counter(words)


Related Topics



Leave a reply



Submit