gpt4 book ai didi

c - 使用strtok分隔单词并删除, and ()

转载 作者:行者123 更新时间:2023-11-30 16:23:44 25 4
gpt4 key购买 nike

我的程序应该采用一个短语并分隔所有单词并将它们打印在新行上,不带任何“,”,“(”或“)”。这是我的代码。到目前为止,它似乎有效,但如果可能的话,我想改进它。另外,我不知道这是否有问题,但它似乎从单个单词中删除了“(”和“)”,但不是两个都删除了。因此,“(test”或“test)”将按预期仅输出“test”,但“(test)”输出“test)”。不确定这是否可以......无论如何我该如何改进?

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

void function(char *string)
{
const char delim[2] = " ";
char *token;
int n, i, j;

token = strtok(string, delim);
while (token != NULL) {
n = strlen(token);
if (strstr(token, ",")) {
for (i = j = 0; i < n; i++) {
if (token[i] != ',')
token[j++] = token[i];
}
token[j] = '\0';
}else if (strstr(token, "(")) {
for (i = j = 0; i < n; i++) {
if (token[i] != '(')
token[j++] = token[i];
}
token[j] = '\0';
} else if (strstr(token, ")")) {
for (i = j = 0; i < n; i++) {
if (token[i] != ')')
token[j++] = token[i];
}
token[j] = '\0';
}

printf("%s\n", token);
token = strtok(NULL, delim);
}
}

int main(void)
{
char test[80] = "The next appointment is on the 7.1.2019, 10:00 a.m., in HS 1 (Building C)";
char input[80];

gets(input);
function(test);
function(input);
return 0;
}

最佳答案

您可以像下面的代码一样进行操作:

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

void function(char *string)
{
const char delim[10] = " ,()";
char *token = strtok(string, delim);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delim);
}
}

int main(void)
{
char test[80] = "The next appointment is on the 7.1.2019, 10:00 a.m., in HS 1 (Building C)";

function(test);

return 0;
}

解释:

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.

参见http://man7.org/linux/man-pages/man3/strtok.3.html

关于c - 使用strtok分隔单词并删除, and (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915484/

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