Counting words in a string - c programming

后端 未结 12 2135
有刺的猬
有刺的猬 2020-12-07 01:52

I need to write a function that will count words in a string. For the purpose of this assignment, a \"word\" is defined to be a sequence of non-null, non-whitespace characte

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 02:15

    I found the posted question after finishing my function for a C class I'm taking. I saw some good ideas from code people have posted above. Here's what I had come up with for an answer. It certainly is not as concise as other's, but it does work. Maybe this will help someone in the future.

    My function receives an array of chars in. I then set a pointer to the array to speed up the function if it was scaled up. Next I found the length of the string to loop over. I then use the length of the string as the max for the 'for' loop. I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation. If pointer is valid then increment to next array index. The word counter is incremented when the first two tests fail. The function then will increment over any number of spaces until the next valid char is found. The function ends when null '\0' or a new line '\n' character is found. Function will increment count one last time right before it exit to account for the word preceding null or newline. Function returns count to the calling function.

    #include 
    
    char wordCount(char array[]) {
        char *pointer;    //Declare pointer type char
        pointer = &array[0];  //Pointer to array
    
        int count; //Holder for word count
        count = 0; //Initialize to 0.
    
        long len;  //Holder for length of passed sentence
        len = strlen(array);  //Set len to length of string
    
        for (int i = 0; i < len; i++){
    
            //Is char punctuation?
            if (ispunct(*(pointer)) == 1) {
                pointer += 1;
                continue;
            }
            //Is the char a valid character?
            if (isalpha(*(pointer)) == 1) {
                pointer += 1;
                continue;
            }
            //Not a valid char.  Increment counter.
            count++;
    
            //Look out for those empty spaces. Don't count previous
            //word until hitting the end of the spaces.
            if (*(pointer) == ' ') {
                do {
                    pointer += 1;
                } while (*(pointer) == ' ');
            }
    
            //Important, check for end of the string
            //or newline characters.
            if (*pointer == '\0' || *pointer == '\n') {
                count++;
                return(count);
            }
        }
        //Redundent return statement.
        count++;
        return(count);
    }
    

提交回复
热议问题