gpt4 book ai didi

c - 将多个字符串传递给函数

转载 作者:行者123 更新时间:2023-11-30 19:20:41 25 4
gpt4 key购买 nike

我正在尝试将多个字符串读入函数中进行处理。这些指令是将每个字符串传递到函数中(而不是创建二维字符串数组)。参数必须保持不变。这是我尝试过的

#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 也会识别它,因为我需要在 main 中打印单词/字符计数,而不返回 中的实际计数转换

最佳答案

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

    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 中找到。

关于c - 将多个字符串传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com