Count words in a string
#1

Hey I've wondered how it's possible to count how many words are in a string, REGARDLESS of how many spaces are in them.

Something like:
pawn Код:
stock CountWords(string[], &words, &spaces)
{
    ///
}

new wordInt;
new spaceInt;

CountWord("This is a test", wordInt, spaceInt);

printf("\"This is a test\" has %d words and %d spaces", wordInt, spaceInt);
//Would print "This is a test" has 4 words and 3 spaces
I know it's possible with sscanf somehow(or atleast I think), but I just can't get my way around it. Can someone show me how to reach a solution? Or guide me through which functions to use? I'm lost.


EDIT
Solved! Managed to think of something. You may use it if you want.
pawn Код:
stock IsChar(ch)
{
    return ( 'a' <= ch <= 'z' || 'A' <= ch <= 'Z' || '0' <= ch <= '9' );
}

stock FindCharAfterSpace(string[], pos)
{
    new index = pos;
    while((string[index] == ' ' || !IsChar(string[index])) && index < strlen(string)) index++;
    return index;
}

stock FindCharBeforeSpace(string[], pos)
{
    new index = pos;
    while(string[index] == ' ' || !IsChar(string[index])) index--;
    return index;
}

stock CountWords(string[], &words, &spaces)
{
    words = 0;
    spaces = 0;
   
    new wordCount;
    new spaceCount;
    if(IsChar(string[0])) wordCount++;
    for(new i = 0; i < strlen(string); i++) {
        if(string[i] == ' ' || !IsChar(string[i])) {
            if(IsChar(string[FindCharBeforeSpace(string, i)]) && IsChar(string[FindCharAfterSpace(string, i)])) wordCount++, i = FindCharAfterSpace(string, i);
        }
    }
   
    for(new i = 0; i < strlen(string); i++) if(string[i] == ' ') spaceCount++;
   
    words = wordCount;
    spaces = spaceCount;

    printf(" \"%s\" has %d words and %d spaces", string, words, spaces);
}

//Debug test:
public OnFilterScriptInit()
{
    new w = 0, s = 0;
    CountWords("Test 1 2 3    4", w, s);
    CountWords("Test 1 2 3 4", w, s);
    CountWords("Test 1", w, s);
    CountWords("Test", w, s);
    CountWords("Is this some kind   of fuckinG         joke?????? Huh", w, s);
    return 1;
}
pawn Код:
//These printed:
/* "Test 1 2 3    4" has 5 words and 7 spaces
 "Test 1 2 3 4" has 5 words and 4 spaces
 "Test 1" has 2 words and 1 spaces
 "Test" has 1 words and 0 spaces
 "Is this some kind   of fuckinG         joke?????? Huh" has 8 words and 17 spaces*/
Reply


Messages In This Thread
[SOLVED] Count words in a string - by [XST]O_x - 27.08.2014, 18:54
Re: Count words in a string - by Rudy_ - 27.08.2014, 19:02
Re: Count words in a string - by TakeiT - 27.08.2014, 19:05
Re: Count words in a string - by ThePhenix - 27.08.2014, 19:20
Re: Count words in a string - by CutX - 27.08.2014, 19:35
Re: Count words in a string - by [XST]O_x - 27.08.2014, 20:04
Re: Count words in a string - by Rudy_ - 27.08.2014, 20:28

Forum Jump:


Users browsing this thread: 1 Guest(s)