gpt4 book ai didi

C - 将字符复制到字符*

转载 作者:行者123 更新时间:2023-11-30 20:33:08 26 4
gpt4 key购买 nike

我在尝试将 char 设置为 char*(“字符串”)时遇到了一些麻烦

我得到了lines,这是我之前获取的所有txt行,现在我尝试将一个char分配给我的char*,以过滤它。

这是我的实际代码:

void TreatDatas(char** lignes, int sizeLignes){ // all the lines, and the size of it.
char** finalArray;
finalArray = malloc(2048 * sizeof(char*));
int sizeOfFinalArray = 0;

int i;
int j;

char* s;
char* savedCurrentString = "";
int sizeOfCurrentString = 0;

for (i = 0; i< sizeLignes; i++){
s = lignes[i];
for (j = 0; j < strlen(s); j++){ // I don't pass the first condition the first loop
if (s[j] == ',' || s[j] == '.' || s[j] == ' ' || s[j] == '\n' || s[j] == ';' || s[j] == ':'){ // Separators list
finalArray[sizeOfFinalArray] = malloc(strlen(savedCurrentString) + 1);
strcpy(finalArray[sizeOfFinalArray], savedCurrentString);
savedCurrentString = "";
sizeOfCurrentString = 0;
}else{

printf("%c , %s \n", s[j], savedCurrentString); // L - ""
printf("%d", sizeOfCurrentString); // 0
strncpy(savedCurrentString, s[j], 1); // error here

}
}
}
free(finalArray);
}

最佳答案

好吧,我对代码做了一些更改,现在更好了,但似乎重复了一些元素。我不知道为什么。抱歉,我是 C 初学者,但我很好奇并试图了解它是如何工作的。

void TreatDatas(char** lignes, int sizeLignes){

char** finalArray;
finalArray = malloc(2048 * sizeof(char*));
int sizeOfFinalArray = 0;

int i;
int j;

char* s;
char* savedCurrentString = "";
int sizeOfCurrentString = 0;

for (i = 0; i< sizeLignes; i++){
s = lignes[i];
printf("line : %d \n %s \n", i, s);
StringSpliter(s);
// for (j = 0; j < strlen(s); j++){
// finalArray[sizeOfFinalArray] = malloc(strlen(savedCurrentString) + 1);
// }
}
free(finalArray);
}

char * StringSpliter(char* input){
char separators[5][2] = {" ", ",", ";", ":", "."};

char ** buffer;
int bufferSize = 0;

int i;

for (i = 0; i < 5; i++){

char* token = strtok(input, separators[i]);
printf("%s", token);

while( token != NULL )
{
printf( " %s\n", token );

token = strtok(NULL, separators[i]);
}

}

printf("\n");

return "OSEF";
}

My output

关于C - 将字符复制到字符*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264304/

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