你做
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