該程式的目標是將編輯字串中的給定單詞替換為完整句子中的星號。
例如,給出一個完整的句子:“The quick brown fox jumps over the lazy dog”并編輯字串:“the, jumps,lazy”,輸出為“*** quick brown fox ***** 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;
}
提前致謝 :)
uj5u.com熱心網友回復:
請您嘗試以下方法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char fullSentence[] = "The quick brown fox jumps over the lazy dog";
char **fullArray = NULL; // tokenized array for fullSentence
int m = 0; // array length of fullArray
char redactString[] = "the, jumps, lazy";
char **redactArray = NULL; // tokenized array for redactString
int n = 0; // array length of redactArray
char *token;
int i, j, k;
for (token = strtok(fullSentence, " "); token != NULL; token = strtok(NULL, " ")) {
fullArray = realloc(fullArray, (m 1) * sizeof(*fullArray));
fullArray[m] = malloc(strlen(token) 1);
strncpy(fullArray[m], token, strlen(token) 1);
m ;
}
for (token = strtok(redactString, ", "); token != NULL; token = strtok(NULL, ", ")) {
redactArray = realloc(redactArray, (n 1) * sizeof(*redactArray));
redactArray[n] = malloc(strlen(token) 1);
strncpy(redactArray[n], token, strlen(token) 1);
n ;
}
// compare the words one by one ignoring case
for (i = 0; i < m; i ) {
for (j = 0; j < n; j ) {
if (strcasecmp(fullArray[i], redactArray[j]) == 0) {
// the words match. redact the word in fullArray[i]
for (k = 0; k < strlen(fullArray[i]); k ) {
fullArray[i][k] = '*';
}
}
}
}
// print the redacted string
for (i = 0; i < m; i ) {
printf("%s%s", fullArray[i], i == m - 1 ? "\n" : " ");
}
return 0;
}
輸出:
*** quick brown fox ***** over *** **** dog
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433689.html
上一篇:使用dplyr計算一個字串并在R的新列中對它們求和?
下一篇:根據給定的字串加/減/或乘
