gpt4 book ai didi

在 C 中从 char 数组创建字符串

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

我有一段代码循环遍历字符数组字符串来尝试检测单词。它循环遍历,如果检测到 A - Z 或 a - z 或 _ (下划线),它会将其添加到 char 数组中。因为它们是单词,所以我需要的是能够将它们放入一个字符串中,然后我可以使用另一个函数来检查该字符串,然后可以将其丢弃。这是我的功能:

char wholeProgramStr2[20000];
char wordToCheck[100] ="";

IdentiferFinder(char *tmp){
//find the identifiers
int count = 0;
int i;
for (i = 0; i < strlen(tmp); ++i){
Ascii = toascii(tmp[i]);
if ((Ascii >= 65 && Ascii <= 90) || (Ascii >= 97 && Ascii <= 122) || (Ascii == 95))
{
wordToCheck[i] = tmp[i];
count++;
printf("%c",wordToCheck[i]);
}
else {
if (count != 0){
printf("\n");
}
count = 0;
}
}
printf("\n");
}

目前我可以看到所有单词,因为它将它们打印在单独的行上。

WholeProgram2 的内容是文件中所有行的内容。它是 *tmp 参数。

谢谢。

最佳答案

您描述了将大字符串分解为小字符串(单词)。
假设您使用普通分隔符进行解析,例如空格或制表符或换行符:

这是一个三步方法:
首先,获取有关源字符串的信息。
第二,动态创建目标数组以满足您的大小需求
第三,循环 strtok() 以填充目标字符串数组 (char **)

(第四个是释放创建的内存,这是您需要做的)
提示:原型(prototype)可能如下所示:
//void Free2DCharArray(char **a, int numWords);

代码示例:

void FindWords(char **words, char *source);
void GetStringParams(char *source, int *longest, int *wordCount);
char ** Create2DCharArray(char **a, int numWords, int maxWordLen);
#define DELIM " \n\t"

int main(void)
{
int longestWord = 0, WordCount = 0;
char **words={0};
char string[]="this is a bunch of test words";

//Get number of words, and longest word, use in allocating memory
GetStringParams(string, &longestWord, &WordCount);

//create array of strings with information from source string
words = Create2DCharArray(words, WordCount, longestWord);

//populate array of strings with words
FindWords(words, string);

//Do not forget to free words (left for you to do)
return 0;
}

void GetStringParams(char *source, int *longest, int *wordCount)
{
char *tok;
int i=-1, Len = 0, KeepLen = 0;
char *cpyString = 0;
cpyString = calloc(strlen(source)+1, 1);
strcpy(cpyString, source);
tok=strtok(source, DELIM);
while(tok)
{
(*wordCount)++;
Len = strlen(tok);
if(Len > KeepLen) KeepLen = Len;
tok = strtok(NULL, DELIM);
}
*longest = KeepLen;
strcpy(source, cpyString);//restore contents of source
}

void FindWords(char **words, char *source)
{
char *tok;
int i=-1;

tok = strtok(source, DELIM);
while(tok)
{
strcpy(words[++i], tok);
tok = strtok(NULL, DELIM);
}
}

char ** Create2DCharArray(char **a, int numWords, int maxWordLen)
{
int i;
a = calloc(numWords, sizeof(char *));
if(!a) return a;
for(i=0;i<numWords;i++)
{
a[i] = calloc(maxWordLen + 1, 1);
}
return a;
}

关于在 C 中从 char 数组创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26889402/

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