Multifine
Badges: 9
Rep:
?
#1
Report Thread starter 1 year ago
#1
Write a function named WordCount, which determines the number of words in a “C type” string. The function will have one parameter (the address of the string) and will return the number of words (words are separated by one or more spaces).

*****

Answer 1:
#include <stdio.h>
#include <string.h>
int WordCount(char* str) {
int count = 1;
for(int i = 0; i < strlen(str); i++)
if( str[i] == ' ')
count ++;
return count;
}

Answer 2:
#include <stdio.h>
#include <string.h>

int WordCount(char str[]){
int i, count = 1;
for(i=0;str[i]!='\0';i++)
{
if(str[i]==' ')
{
count++;
}
}
return count;
}

int main()
{
char str[200];
int i,j = 0, count = 0, len;
printf("Enter word: ");
scanf("%[^\n]s",str);

printf("count = %d\n",WordCount(str));
return 0;
}

*****

For this question, is answer 1 or answer 2 the correct way if the "C-type" string is an array of characters with an end of string mark following the last character?
0
reply
winterscoming
Badges: 19
Rep:
?
#2
Report 1 year ago
#2
They're both "correct" since they both give you exactly the same result, so you can use them interchangably really, and it's mostly about personal preference/style. 'strlen' finds the end of a string by searching for the nul '\0' character anyway.

So with that in mind, a reason why some people might prefer the 2nd option is that 'strlen' is already looping through the whole string to find the nul '\0' character, but choose whichever you prefer!

Some people might also write it a third way using a pointer as an "iterator", but this is also just another matter of style and personal choice really - e.g.
Code:
int WordCount(char str[]) {
  int count = 1;
  for (char *iter = str; *iter != '\0'; iter++)  {
      if (*iter == ' ') {
          count++;
      }
  }
  return count;
}
Last edited by winterscoming; 1 year ago
0
reply
X

Quick Reply

Attached files
Write a reply...
Reply
new posts
Back
to top
Latest
My Feed

See more of what you like on
The Student Room

You can personalise what you see on TSR. Tell us a little about yourself to get started.

Personalise

What support do you need with your UCAS application?

I need help researching unis (21)
14.48%
I need help researching courses (8)
5.52%
I need help with filling out the application form (7)
4.83%
I need help with my personal statement (60)
41.38%
I need help with understanding how to make my application stand out (36)
24.83%
I need help with something else (let us know in the thread!) (3)
2.07%
I'm feeling confident about my application and don't need any help at the moment (10)
6.9%

Watched Threads

View All