2012-03-12 12 views
0

私は、文字列から2つのサブストリングを抽出しようとしています:予測可能な形式で文字列から2つのサブストリングを抽出

char test[] = "today=Monday;tomorrow=Tuesday"; 
char test1[20]; 
char test2[20]; 

sscanf(test, "today=%s;tomorrow=%s", test1, test2); 

私は今日プリントアウトするとき、私は月曜日を得るだけでなく、文字列の残りの部分。私はtest1を月曜日にし、test2を火曜日にしたい。 sscanfを正しく使用するには?

答えて

0

% sのタグを使用する場合は、次の空白が見つかるまで、sscanf関数は、このマニュアルによると、読み取りますhttp://www.cplusplus.com/reference/clibrary/cstdio/sscanf/

したがって、たとえば、あなたが

char test[] = "today=Monday tomorrow=Tuesday"; 
+0

元のテスト文字列を変更できない場合はどうすればできますか? – egidra

+0

元の文字列を変更できない場合は、whileループの組み合わせを使用してみてください。 =が出現するまでテスト中の文字をループします。次に、あなたがに遭遇するまで、test1に文字を保存し始めます。 test2も同様に繰り返します。 – mkasberg

+0

このように 'int i = 0; while(test [i]!= '='){i ++}; int j = 0; while(test [i]!= ';'){test1 [j] = test [i];私は+ +; j ++} ' – mkasberg

3

にあなたの文字列を変更することができますキーは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を使用して便利かもしれません
関連する問題