你做
if (count == 0) {
array[count] = saved;
count ++;
}
這意味着你保存saved
的地址爲array[count]
。在這個操作中沒有字符串被複制。
然後你做:
if (array[count] == saved) {
printf("FOUND!");
}
上述比較存儲在array[count]
與存儲在saved
地址的值。此操作不會比較存儲在其中的字符串。
因此,如果array[count]
指向一個字符串「愛麗絲」和saved
點存儲在另一個存儲位置0xdeadbeef
字符串「愛麗絲」的地址0x1234abcd
然後array[count] == string
不會一樣在這種情況下0x1234abcd == 0xdeadbeef
正在做。比較你需要做的兩個字符串strcmp (array[count], saved) == 0
。
注意,你
while (i < count) {
if (array[count] == saved) {
printf("FOUND!");
}
i++;
}
在上面的代碼,你已經增加i
但count
是靜態的一個階段,並且不依賴於i
訪問array
。它應該是array[i]
你做
if (count == 0)
{
array[count] = saved;
count ++
}
if (count > 0)
{
/* Here you try to search if the 'saved' is in the aray
but if it is not there you have NOT inserted it anywhere
into the array
*/
}
因爲你不輸入由saved
指出,當除了第一個count > 0
所以唯一的字符串不被存儲在array
的字符串。因此,只要發現它不在if (count > 0)
區塊中,就應該將新的刺刺保存到陣列中。如以下段落中所述:
if (count > 0)
{
int i = 0;
while (i < count)
{
/* note use of strcmp */
if (strcmp (array[i], saved) == 0)
{
printf ("FOUND!"); /* if it was found break immediately */
break;
}
i++;
}
if (i == count) /* if there was no match then only i == count */
{ /* in other cases when dupes are there i<count as we used break */
array[count] = saved;
count++;
}
}
這是修改的代碼,它反映了上述更改。
#include <stdio.h>
#include <string.h>
int main (void)
{
char str[] =
"INVITE sip:[email protected] SIP/2.0\nCall-ID: [email protected] To: <sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;<sip:[email protected]>;";
char *tch;
char *saved;
char *array[50];
int count = 0, i;
tch = strtok (str, "<:;>");
while (tch != NULL)
{
int savenext = 0;
if (!strcmp (tch, "sip"))
{
savenext = 1;
}
// printf ("%s\n", tch);
tch = strtok (NULL, "<:;>");
if (savenext == 1)
{
saved = tch;
}
if (count == 0)
{
array[count] = saved;
count++;
}
else if ((count > 0) && (savenext == 1))
{
int i = 0;
while (i < count)
{
if (strcmp (array[i], saved) == 0)
{
printf ("FOUND!");
break;
}
i++;
}
if (i == count)
{
array[count] = saved;
count++;
}
}
}
for (i = 0; i < count; i++)
printf ("\n%s", array[i]);
}
EDIT1:
回答您的評論: 說出strtok
已經匹配的「SIP」,那麼它使saveptr = 1
讀取,在未來和tch
道理,即用戶名信息並保存它在saveptr
的幫助下轉化爲array
。在下一個迭代中注意,tch
指向存儲在數組中的用戶名信息。所以strcmp
失敗,因爲它不是「sip」(包含用戶名信息)。所以在這種情況下,saved
雖然沒有修改,但仍然保持先前的值,它再次進入if (count > 0)
塊。因此,在您的過程中,將檢查一個用戶信息兩次。你應該做
if ((count > 0) && (savenext == 1))
{
/* Then insert */
}
上面的代碼說什麼,如果要保存在array
saveptr ==
那麼saved
需求,這就是爲什麼你拿了旗子savenext
。
我也更新了代碼。現在它正確地告訴我們只有一個重複。
我建議重新設計代碼並使其更清潔一些。可能你希望再細看一下指針,以使其更好。
究竟如何你想解析。請詳細說明一下。我無法理解。 – phoxis 2011-06-06 17:01:56
我想提取所有的「愛麗絲」值,並檢查是否有任何使用兩次。如果發現兩次,那麼它應該打印一條消息。 – tzoukos 2011-06-06 17:14:59
說,我們提取值alice1,alice2,alice,alice4,alice ....然後程序必須看到'alice'在字符串中找到兩次並打印警報。我希望我讓自己更清楚:) – tzoukos 2011-06-06 17:22:22