在将字符串拆分为令牌以将这些令牌返回转换为原始字符串(带标点符号和原始区分大小写)之后,有没有办法?
我相当肯定会调用strcat,但是保持原始字符串的标点符号是一个很好的方法。区分大小写?
假设在将它们连接回原始字符串的结构之前,我需要单独修改每个标记。
编辑:标题已重新编辑&澄清,我希望。
char* msg = malloc(10000);
char* msg2 = malloc(10000);
char* buffer;
char buffer2[10000];
printf("input: \n");
fgets(msg, 9999, stdin);
msg2 = strdup(msg);
buffer = strtok(msg2, " ;,.!?\n");
Node* ptr; // assume this is initialized to a linked list containing 2 strings per node (str, str2)
while (buffer) {
for (int i = 0; i < strlen(buffer); i++) { //strcmp is case-sensitive
if (isalpha(buffer[i])) {
buffer[i] = tolower(buffer[i]);
}
}
while (ptr) {
if ((ptr != NULL) && (strcmp(ptr->str, ptr->str2) != 0)) {
buffer = ptr->str2; // modifies the token
break;
}
}
ptr = ptr->next;
}
strcat(buffer2, " "); // this will concatenate the modified tokens back together with spaces
strcat(buffer2, buffer); // but I lose the original string's structure (i.e.: punctuation, case-sensitivity)
buffer = strtok(NULL, " ;,.!?\n");
printf("%s", buffer2); // so how should I get the original string's structure back with the modified tokens?
答案 0 :(得分:1)
如果您想使用strtok()
并希望稍后访问原始字符串,请保留原始字符串的副本,因为strtok()将销毁原始字符串。
// we have char *st ;
char *tem = malloc(strlen(st)+1);
strcpy(tem, st);
现在您可以稍后将tem作为原始字符串访问。