如何在C中编写一个计算单词数量的函数。

huangapple go评论70阅读模式
英文:

How to write a function in c that counts words

问题

以下是翻译好的部分:

"I had an exam yesterday in which one of the questions was about counting words in a given string.

The definition of word would be a portion of a string that is divided by spaces and/or the beginning/end of the string

I am new to C, and was not able to create a condition where it increases the counter word when you find “space (characters) space”

int count_words(char *str)
{
    int i = 0;
    int word = 2;
    while (str[i])
    { 
        if (str[i] == ' ')
        {
            int l = 1;
            while (str[i + l])
            {
                l++;
            }
            if (l != 1)
            {
                word++;
            }
        }
        i++;
    }
    return word;
}

请注意,我已经将代码部分翻译成中文。

英文:

I had an exam yesterday in which one of the questions was about counting words in a given string.

The definition of word would be a portion of a string that is divided by spaces and/or the beginning/end of the string

I am new to C, and was not able to create a condition where it increases the counter word when you find “space (characters) space”

int count_words(char *str)
int i = 0;
int word = 2;
while (str[i])
{ 
     if (str[i] == ‘ ‘)
     {
         int l = 1;
         while (str[i + l]
         {
             l++;
         }
         if (l != 1)
         {
             word++;
         }
      }
}

答案1

得分: 1

以下是翻译好的部分:

对于开始,函数应该声明如下:

size_t count_words(const char *str);

函数参数应该使用`const`关键字声明,因为传递的字符串在函数内部不会被更改,函数返回类型应该是`size_t`,这与标准字符串函数`strlen`的返回类型相同。

不清楚为什么在您的函数中初始化变量`word`为`2`

int word = 2;

或者变量`i`在函数内部未被更改。

函数可以如下所示,如下演示程序所示:

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

size_t count_words( const char *s )
{
    size_t n = 0;

    while ( *s )
    {
        while ( isspace( ( unsigned char )*s ) ) ++s;

        if ( *s )
        {
            ++n;
            while ( *s && !isspace( ( unsigned char )*s ) ) ++s;
        }
    }

    return n;
}

int main( void )
{
    const char *s = "How to write a function in c that counts words";

    size_t n = count_words( s );

    printf( "The string \"%s\"\ncontains %zu words\n", s, n );
}

程序输出是

The string "How to write a function in c that counts words"
contains 10 words

如果仅使用空格字符' '作为分隔符,那么应删除头文件<ctype.h>,函数将如下所示:

size_t count_words( const char *s )
{
    size_t n = 0;

    while ( *s )
    {
        while ( *s == ' ' ) ++s;

        if ( *s )
        {
            ++n;
            while ( *s && *s != ' ' ) ++s;
        }
    }

    return n;
}

可以处理任何分隔符的更通用的函数可以如下所示:

size_t count_words( const char *s, const char *delim )
{
    size_t n = 0;

    while (*s)
    {
        s += strspn( s, delim );

        if (*s)
        {
            ++n;
            s += strcspn( s, delim );
        }
    }

    return n;
}

该函数具有第二个参数,用于指定分隔符。例如,函数可以这样调用:

size_t n = count_words( s, " \t?!:;,." );
英文:

For starters the function should be declared like

size_t count_words(const char *str);

The function parameter should be declared with the qualifier const because the passed string is not being changed within the function and the function return type should be size_t that is the same return type as for example of standard string function strlen.

It is unclear why the variable word in your function is initialized by 2

int word = 2;

Or the variable i is not being changed within the function.

The function can look the following way as shown in the demonstration program below

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

size_t count_words( const char *s )
{
	size_t n = 0;

	while ( *s )
	{
		while ( isspace( ( unsigned char )*s ) ) ++s;

		if ( *s )
		{
			++n;
			while ( *s && !isspace( ( unsigned char )*s ) ) ++s;
		}
	}

	return n;
}

int main( void )
{
	const char *s = "How to write a function in c that counts words";

	size_t n = count_words( s );

	printf( "The string \"%s\"\ncontains %zu words\n", s, n );
}

The program output is

The string "How to write a function in c that counts words"
contains 10 words

If to use as delimiters only the space character ' ' then the header <ctype.h> should be removed and the function will look like

size_t count_words( const char *s )
{
	size_t n = 0;

	while ( *s )
	{
		while ( *s == ' ' ) ++s;

		if ( *s )
		{
			++n;
			while ( *s && *s != ' ' ) ++s;
		}
	}

	return n;
}

A more general function that can process any delimiters can look the following way

size_t count_words( const char *s, const char *delim )
{
	size_t n = 0;

	while (*s)
	{
		s += strspn( s, delim );

		if (*s)
		{
			++n;
			s += strcspn( s, delim );
		}
	}

	return n;
}

The function has a second parameter that specifies delimiters. For example the function can be called loke

size_t n = count_words( s, " \t?!:;,." );

答案2

得分: 0

请参照以下方式尝试:

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

# define MaxBufferSize 50
void main(){
    int count = 0, size;
    char str[MaxBufferSize + 2];
    printf("Enter string (最多50个字符): ");
    if(fgets(str, sizeof(str), stdin)) {
        if(strlen(str) > MaxBufferSize) printf("已超过最大字符数,仅使用前50个字符!!!\n");
        str[strcspn(str, "\n")] = '
# include <stdio.h>
# include <string.h>

# define MaxBufferSize 50
void main(){
    int count = 0, size;
    char str[MaxBufferSize + 2];
    printf("Enter string (最多50个字符): ");
    if(fgets(str, sizeof(str), stdin)) {
        if(strlen(str) > MaxBufferSize) printf("已超过最大字符数,仅使用前50个字符!!!\n");
        str[strcspn(str, "\n")] = '\0';
    }
    size = strlen(str);
    int i = 0;
    if(size == 0) printf("未输入任何内容\n");
    else {
        while(i < size){
            while(!isalnum(str[i]) && i < size) i++; // 忽略所有空格和其他字符
            if(str[i] == '\0') break;
            while(isalnum(str[i]) && i < size) i++; // 包括所有单词和数字
            count++;
        }
        printf("字符串中的单词数: %d\n", count);
    }
}
'
;
} size = strlen(str); int i = 0; if(size == 0) printf("未输入任何内容\n"); else { while(i < size){ while(!isalnum(str[i]) && i < size) i++; // 忽略所有空格和其他字符 if(str[i] == '
# include <stdio.h>
# include <string.h>

# define MaxBufferSize 50
void main(){
    int count = 0, size;
    char str[MaxBufferSize + 2];
    printf("Enter string (最多50个字符): ");
    if(fgets(str, sizeof(str), stdin)) {
        if(strlen(str) > MaxBufferSize) printf("已超过最大字符数,仅使用前50个字符!!!\n");
        str[strcspn(str, "\n")] = '\0';
    }
    size = strlen(str);
    int i = 0;
    if(size == 0) printf("未输入任何内容\n");
    else {
        while(i < size){
            while(!isalnum(str[i]) && i < size) i++; // 忽略所有空格和其他字符
            if(str[i] == '\0') break;
            while(isalnum(str[i]) && i < size) i++; // 包括所有单词和数字
            count++;
        }
        printf("字符串中的单词数: %d\n", count);
    }
}
'
) break;
while(isalnum(str[i]) && i < size) i++; // 包括所有单词和数字 count++; } printf("字符串中的单词数: %d\n", count); } }

希望对你有所帮助...! 如何在C中编写一个计算单词数量的函数。

英文:

Try this way:

# include&lt;stdio.h&gt;
# include&lt;string.h&gt;

# define MaxBufferSize 50
void main(){
    int count =0, size;
    char str[MaxBufferSize+2];
    printf(&quot;Enter string(max char 50 only): &quot;);
    if(fgets(str,sizeof(str), stdin)) {
        if(strlen(str) &gt; MaxBufferSize) printf(&quot;Max chars exceeded so chars before the limit were used!!!\n&quot;);
        str[strcspn(str, &quot;\n&quot;)] = &#39;
# include&lt;stdio.h&gt;
# include&lt;string.h&gt;
# define MaxBufferSize 50
void main(){
int count =0, size;
char str[MaxBufferSize+2];
printf(&quot;Enter string(max char 50 only): &quot;);
if(fgets(str,sizeof(str), stdin)) {
if(strlen(str) &gt; MaxBufferSize) printf(&quot;Max chars exceeded so chars before the limit were used!!!\n&quot;);
str[strcspn(str, &quot;\n&quot;)] = &#39;\0&#39;;
}
size = strlen(str);
int i=0;
if(size == 0) printf(&quot;Nothing entered\n&quot;);
else {
while(i&lt;size){
while(!isalnum(str[i]) &amp;&amp; i&lt;size) i++;// ignores all spaces and other chars
if(str[i] == &#39;\0&#39;) break;
while(isalnum(str[i]) &amp;&amp; i&lt;size) i++;// includes all words and numbers 
count++;
}
printf(&quot;Words in string: %d\n&quot;,count);
}
}
&#39;; } size = strlen(str); int i=0; if(size == 0) printf(&quot;Nothing entered\n&quot;); else { while(i&lt;size){ while(!isalnum(str[i]) &amp;&amp; i&lt;size) i++;// ignores all spaces and other chars if(str[i] == &#39;
# include&lt;stdio.h&gt;
# include&lt;string.h&gt;
# define MaxBufferSize 50
void main(){
int count =0, size;
char str[MaxBufferSize+2];
printf(&quot;Enter string(max char 50 only): &quot;);
if(fgets(str,sizeof(str), stdin)) {
if(strlen(str) &gt; MaxBufferSize) printf(&quot;Max chars exceeded so chars before the limit were used!!!\n&quot;);
str[strcspn(str, &quot;\n&quot;)] = &#39;\0&#39;;
}
size = strlen(str);
int i=0;
if(size == 0) printf(&quot;Nothing entered\n&quot;);
else {
while(i&lt;size){
while(!isalnum(str[i]) &amp;&amp; i&lt;size) i++;// ignores all spaces and other chars
if(str[i] == &#39;\0&#39;) break;
while(isalnum(str[i]) &amp;&amp; i&lt;size) i++;// includes all words and numbers 
count++;
}
printf(&quot;Words in string: %d\n&quot;,count);
}
}
&#39;) break; while(isalnum(str[i]) &amp;&amp; i&lt;size) i++;// includes all words and numbers count++; } printf(&quot;Words in string: %d\n&quot;,count); } }

hope it helps...! 如何在C中编写一个计算单词数量的函数。

答案3

得分: 0

#include <stdio.h>

int count_words(char *str) {
    int i, count = 0;
    int in_word = 0; // Flag to track if we're currently inside a word or not

    // Loop through each character in the string
    for (i = 0; str[i] != '
#include <stdio.h>

int count_words(char *str) {
    int i, count = 0;
    int in_word = 0; // Flag to track if we're currently inside a word or not

    // Loop through each character in the string
    for (i = 0; str[i] != '\0'; i++) {
        // If current character is not a space or newline and we're not already inside a word, increment word count
        if ((str[i] != ' ' && str[i] != '\n') && !in_word) {
            count++;
            in_word = 1; // Set flag to indicate we're currently inside a word
        }
        // If current character is a space or newline, set flag to indicate we're not inside a word
        else if (str[i] == ' ' || str[i] == '\n') {
            in_word = 0;
        }
    }

    return count;
}
'
; i++) {
// If current character is not a space or newline and we're not already inside a word, increment word count if ((str[i] != ' ' && str[i] != '\n') && !in_word) { count++; in_word = 1; // Set flag to indicate we're currently inside a word } // If current character is a space or newline, set flag to indicate we're not inside a word else if (str[i] == ' ' || str[i] == '\n') { in_word = 0; } } return count; }
英文:
    #include &lt;stdio.h&gt;

int count_words(char *str) {
    int i, count=0;
    int in_word = 0; // Flag to track if we&#39;re currently inside a word or not
    
    // Loop through each character in the string
    for(i=0; str[i]!=&#39;
    #include &lt;stdio.h&gt;
int count_words(char *str) {
int i, count=0;
int in_word = 0; // Flag to track if we&#39;re currently inside a word or not
// Loop through each character in the string
for(i=0; str[i]!=&#39;\0&#39;; i++) {
// If current character is not a space or newline and we&#39;re not already inside a word, increment word count
if((str[i]!=&#39; &#39; &amp;&amp; str[i]!=&#39;\n&#39;) &amp;&amp; !in_word) {
count++;
in_word = 1; // Set flag to indicate we&#39;re currently inside a word
}
// If current character is a space or newline, set flag to indicate we&#39;re not inside a word
else if(str[i]==&#39; &#39; || str[i]==&#39;\n&#39;) {
in_word = 0;
}
}
return count;
}
&#39;; i++) { // If current character is not a space or newline and we&#39;re not already inside a word, increment word count if((str[i]!=&#39; &#39; &amp;&amp; str[i]!=&#39;\n&#39;) &amp;&amp; !in_word) { count++; in_word = 1; // Set flag to indicate we&#39;re currently inside a word } // If current character is a space or newline, set flag to indicate we&#39;re not inside a word else if(str[i]==&#39; &#39; || str[i]==&#39;\n&#39;) { in_word = 0; } } return count; }

答案4

得分: -1

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

void main()
{
    char s[200];
    int count = 0, i;

    printf("输入字符串:\n");
    scanf("%[^\n]s", s);
    for (i = 0; s[i] != '
#include <stdio.h>
#include <string.h>

void main()
{
    char s[200];
    int count = 0, i;

    printf("输入字符串:\n");
    scanf("%[^\n]s", s);
    for (i = 0; s[i] != '\0'; i++)
    {
        if (s[i] == ' ' && s[i+1] != ' ')
            count++;    
    }
    printf("给定字符串中的单词数为: %d\n", count + 1);
}
'
; i++)
{ if (s[i] == ' ' && s[i+1] != ' ') count++; } printf("给定字符串中的单词数为: %d\n", count + 1); }

使用这段代码,它肯定可以正常运行 如何在C中编写一个计算单词数量的函数。

英文:
    #include &lt;stdio.h&gt;
    #include &lt;string.h&gt;
     
    void main()
    {
        char s[200];
        int count = 0, i;
     
        printf(&quot;Enter the string:\n&quot;);
        scanf(&quot;%[^\n]s&quot;, s);
        for (i = 0;s[i] != &#39;
    #include &lt;stdio.h&gt;
#include &lt;string.h&gt;
void main()
{
char s[200];
int count = 0, i;
printf(&quot;Enter the string:\n&quot;);
scanf(&quot;%[^\n]s&quot;, s);
for (i = 0;s[i] != &#39;\0&#39;;i++)
{
if (s[i] == &#39; &#39; &amp;&amp; s[i+1] != &#39; &#39;)
count++;    
}
printf(&quot;Number of words in given string are: %d\n&quot;, count + 1);
}
&#39;;i++) { if (s[i] == &#39; &#39; &amp;&amp; s[i+1] != &#39; &#39;) count++; } printf(&quot;Number of words in given string are: %d\n&quot;, count + 1); }

Use this code it will definitely works fine ):

huangapple
  • 本文由 发表于 2023年2月18日 15:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定