我刚刚开始进行C编程,我试着做一个练习,你可以在其中读取(main)中的几个字符串到一个函数中,它在每个字符串中找到单词和字符长度,并从(main)打印字数和字符数在每个字符串中。我不确定如何做到这一点。例如......
#include <stdio.h>
void convert(char s[]), int counts[]);
int main(void)
{
char text1[] = "this IS a String 4 you.";
char text2[] = "This sample has less than 987654321 leTTers."
char text3[] = "Is thIs a string? (definitely)"
void convert(char s[]), int counts[])
{
"""code that reads each string and counts words and characters returning
an array of characters like a[] = {3,5} each number telling how many words
and characters the string has"""
}
答案 0 :(得分:0)
而不是
char text1[] = "this IS a String 4 you.";
char text2[] = "This sample has less than 987654321 leTTers."
char text3[] = "Is thIs a string? (definitely)"
你可以写
char* texts[] = { "this IS a String 4 you.",
"This sample has less than 987654321 leTTers.",
"Is thIs a string? (definitely)",
NULL };
你的功能看起来像这样(C99)
void convert(char* s[], int counts[])
{
for (int i = 0; s[i] != NULL; ++i)
{
...do something with s[i]...
}
答案 1 :(得分:0)
使用二维数组。像
#include <stdio.h>
void convert(char s[]), int counts[]);
int main(void)
{
char text1[][] = {"this IS a String 4 you.","This sample has less than 987654321 leTTers.","Is thIs a string? (definitely)",NULL};
}
void convert(char s[][], int counts[])
{
You can access here s[0][0],s[1][0],s[2][0],... etc.
"""code that reads each string and counts words and characters returning
an array of characters like a[] = {3,5} each number telling how many words
and characters the string has"""
}
答案 2 :(得分:0)
void convert(char s[], int counts[])
{
int l=0, w=0;
for(;s[l]!='\0';l++)
if(l!=0 && s[l]==' ' && s[l-1]!=' ')
w++;
if(s[l-1]!=' ')
w++;
counts[0]=l;
counts[1]=w;
return
}
答案 3 :(得分:0)
如果您打算一次传递所有字符串,只需修改函数声明中的参数并相应调用:
void convert(char [], char [], char []);
int main(void)
{
char text1[] = "some text1";
char text2[] = "some text2";
char text3[] = "some text3";
convert(text1, text2, text3);
}
但是,一种可能更合理的方法是存储指向字符串的指针并使用循环分别为每个字符串调用转换函数:
void convert(char []);
int main(void)
{
char *texts[] = "some text1", "some text2", "some text3";
for (int i = 0; i < 3; i++)
{
convert(texts[i]);
}
}
对于单词/字符计数,您有许多选项。仅举几例: