にあなたの文字列を変更することができますキーはsscanf
にどこで停止するかを伝えることです。
あなたの場合は、セミコロンになるでしょう。
指定しない場合は、%s
は、@mkasbergのように、次の空白まで読むことを示します。
#include <stdio.h>
#include <string.h>
int main() {
char *teststr = "today=Monday;tomorrow=Tuesday";
char today[20];
char tomorrow[20];
sscanf(teststr, "today=%[^;];tomorrow=%s", today, tomorrow);
printf("%s\n", today);
printf("%s\n", tomorrow);
return 0;
}
が生成されます
は
Monday
Tuesday
編集:
#include <stdio.h>
#include <string.h>
int main() {
const char teststr[] = "today=Monday;tomorrow=Tuesday";
const char delims[] = ";=";
char *token, *cp;
char arr[4][20];
unsigned int counter = 0;
unsigned int i;
cp = strdup(teststr);
token = strtok(cp, delims);
strcpy(arr[0], token);
while (token != NULL) {
counter++;
token = strtok(NULL, delims);
if (token != NULL) {
strcpy(arr[counter], token);
}
}
for (i = 0; i < counter; i++) {
printf("arr[%d]: %s\n", i, arr[i]);
}
return 0;
}
結果:
あなたはこの代替
strtok
を使用して便利かもしれません
元のテスト文字列を変更できない場合はどうすればできますか? – egidra
元の文字列を変更できない場合は、whileループの組み合わせを使用してみてください。 =が出現するまでテスト中の文字をループします。次に、あなたがに遭遇するまで、test1に文字を保存し始めます。 test2も同様に繰り返します。 – mkasberg
このように 'int i = 0; while(test [i]!= '='){i ++}; int j = 0; while(test [i]!= ';'){test1 [j] = test [i];私は+ +; j ++} ' – mkasberg