如何在C中将2个字符串提取到单独的数组中
该程序的目标是将编辑字符串中的给定单词替换为完整句子中的星号。
例如给出一个完整的句子:“敏捷的棕色狐狸跳过了懒狗” 并编辑字符串:“the,jumps,lazy”,输出为“***quickbrownfox*****over*******dog”,需要保存在result.txt中。
我的主要想法是在搜索单词之前首先将编辑字符串和完整句子提取到数组中。如果匹配,则完整句子的数组将替换为星号。最后,数组被转换回字符串。
我的代码的问题是,我想将 fullSentence[] 和 redactString[] 中的字符串提取到单独的数组中,但是当我运行此代码时,它输出
... 跳跃, 懒惰的 这 Y├╠╠╠╠╠╠j
这是代码:
int main(void) {
char fullSentence[] = "The quick brown fox jumps over the lazy dog";
int t = 0;
int i = 0;
char **redactArray = NULL;
char *token = strtok(fullSentence, " ");
char redactString[] = "the, jumps, lazy";
int j = 0;
char *p = strtok (redactString, ", ");
char *extractString[3];
for (t = 1; token; ++t) { // Extract fullSentence[]
redactArray = realloc(redactArray, t *sizeof(*redactArray));
redactArray[t - 1] = malloc(strlen(token) + 1);
strncpy(redactArray[t - 1], token, strlen(token) + 1);
token = strtok(NULL, " ");
}
for (i = 0; i < t-1; ++i){
printf("%s\n", redactArray[i]);
}
while (p != NULL) { // Extract redactString[]
extractString[j++] = p;
p = strtok(NULL, ", ");
}
for (j = 0; j < sizeof(extractString); ++j) {
printf("%s\n", extractString[j]);
}
return extractString;
}
提前致谢:)
The goal of this program is to replace given words in redact string into asterisks in a full sentence.
e.g. given a full sentence: "The quick brown fox jumps over the lazy dog"
and redact string: "the, jumps, lazy", the output is "*** quick brown fox ***** over *** **** dog", which needs to be saved in a result.txt.
My main idea is to first extract redact string and a full sentence into an array before searching for a word. If it matches, the array of full sentence is replaced with asterisks. Finally, an array is converted back to a string.
The problem of my code is that I want to extract string from fullSentence[] and redactString[] into individual arrays but when I run this code it output...
The
jumps,
lazy
the
Y├╠╠╠╠╠╠j
This is the code:
int main(void) {
char fullSentence[] = "The quick brown fox jumps over the lazy dog";
int t = 0;
int i = 0;
char **redactArray = NULL;
char *token = strtok(fullSentence, " ");
char redactString[] = "the, jumps, lazy";
int j = 0;
char *p = strtok (redactString, ", ");
char *extractString[3];
for (t = 1; token; ++t) { // Extract fullSentence[]
redactArray = realloc(redactArray, t *sizeof(*redactArray));
redactArray[t - 1] = malloc(strlen(token) + 1);
strncpy(redactArray[t - 1], token, strlen(token) + 1);
token = strtok(NULL, " ");
}
for (i = 0; i < t-1; ++i){
printf("%s\n", redactArray[i]);
}
while (p != NULL) { // Extract redactString[]
extractString[j++] = p;
p = strtok(NULL, ", ");
}
for (j = 0; j < sizeof(extractString); ++j) {
printf("%s\n", extractString[j]);
}
return extractString;
}
Thanks in Advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请您尝试以下操作:
输出:
Would you please try the following:
Output: