将多个字符串传递给函数

时间:2014-02-10 06:53:36

标签: c

我正在尝试将几个字符串读入一个函数进行处理。指令是将每个字符串传递给函数(不创建2d字符串数组)。参数必须保持不变。这是我试过的

#include <stdio.h>
#include <math.h>

void convert(char s[]), int counts[]);

int main(void)
{
     int i = 0;
     int d[2] = {};
     char text0[] = "this IS a String 4 you."; 
     char text1[] = "This sample has less than 987654321 leTTers.";
     while(i<2)
     {
         convert (text[i],d); """ this is wrong but i dont know how to correctly do this
         i = i +1;
     }

}

void convert(char s[]), int counts[])
{

printf("%s this should print text1 and text2", s );

}   

所以我有几个问题。是否有类似于python中的glob模块的特殊字符/运算符,可以正确地为我执行convert (text[i],d)部分,我尝试在每个字符串中读取。此外,int counts[]目的是用函数中的单词和字符计数填充。因此,如果我在函数convert中填写此数组,则主要也会识别它,因为我需要在main中打印单词/字符数,而不返回convert中的实际计数

3 个答案:

答案 0 :(得分:1)

您可以使用临时字符串指针数组来传递所有字符串:

    char text1[] = "This sample has less than 987654321 leTTers.";
    char const * texts[] = { text0, text1 };
    convert (texts, 2, d);
}

void convert(char const * s[], size_t n, int counts[]) 
{
    while(n--) {
        *counts++ = strlen(*s);
        printf("%s\n", *s++);
    }
}   

一些注意事项:

  1. 我将char const添加到函数参数类型中。当函数不更改字符串时,您应该始终这样做。如果您需要更改函数中的字符串,只需删除const
  2. 有额外的参数size_t n将数组数组元素计数传递给函数。 size_t可以找到stddef.h

答案 1 :(得分:0)

我认为你丢失了一个“(”in“void convert(char s []),int counts []);”。 它应该是void convert((char s []),int counts []);

答案 2 :(得分:0)

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

void convert(char s[], int counts[]);

int main(void){
    int i = 0;
    int d[2] = {0};
    char text0[] = "this IS a String 4 you."; 
    char text1[] = "This sample has less than 987654321 leTTers.";
    char *text[] = { text0, text1 };
    for(i=0; i<2; ++i){
        convert (text[i], d);
        printf("%d, %d\n", d[0], d[1]);
    }

}

void convert(char s[], int counts[]){
    printf("%s\n", s );
    {
        char *temp = strdup(s);
        char *word, *delimiter = " \t\n";//Word that are separated by space character.
        int count_w=0, max_len=0;
        for(word = strtok(temp, delimiter); word ; word = strtok(NULL, delimiter)){
            int len = strlen(word);
            if(max_len < len)
                max_len = len;
            ++count_w;
        }
        counts[0] = count_w;
        counts[1] = max_len;
        free(temp);
    }
}