【发布时间】:2015-10-18 17:28:10
【问题描述】:
基本上我想知道是否有可能(如果可以的话)从左到右读取一个字符串,并在找到新字符串后贪婪地终止并追加。例如。
"ABCABCABCABC" 将给出 {"A" "B" "C" "AB" "CA" "BC" "ABC"}
我一整天都在尝试,最终得到的只是代码损坏和程序崩溃。
这就是我所拥有的不起作用。数组定义为 *a[linelen]
for(i =0; i < linelen ;i++)
{
j=0;
k=0;
tempstr[j] = input[i]; // move character from input to tempstring
for(k=0; k< array_size; k++) //search through array
{
tempstr[j] = input[i];
if(*a != tempstr)//(strcmp(a,tempstr)) != 0) // if str not in array
{
printf("%s\n", a[0]); //debug
a[array_size] = tempstr;
//strcpy(a[array_size], tempstr); //copy str into array
array_size++;
memset(tempstr,0,linelen-i); // reset tempstr to empty
j=0;
}
if( *a == tempstr)//(strcmp(a[array_size],tempstr)) == 0)
{
j++;
tempstr[j] = input[i+1];
if(i != linelen -1) // otherwise if tempstr already in array
{
printf("%s\n",a[0]); //debug
j++;
tempstr[j] = input[i+1];
}
else if (i == linelen -1) // if it is the last letter
{
a[array_size] = tempstr;
//strcpy(a[array_size], tempstr); // add to array
break;
}
}
}
}
【问题讨论】:
-
可以吗?当然,很多
strstr()最终应该这样做。可以有效地完成吗?不知道。 -
我不确定你为什么要 BC 和 ABC 而不是 BCA?
-
欢迎来到 Stack Overflow。请尽快阅读About 页面。您应该向我们展示您认为最能处理此问题的代码,并展示它在崩溃之前产生的结果(您至少有一些诊断输出,不是吗?),以便我们可以看到您所看到的。我们会很乐意帮助您解决代码中的问题。我们不会简单地为您编写程序。
-
@maxime:当代码读取A时,它是新的; B是新的; C是新的。然后它读取一个新的 A 但那不是新的,所以它也读取 B,因为 AB 是新的;然后读取CA;然后 BC 是新的,最后 AB 不是新的,但 ABC 是。
-
请查看如何创建 MCVE (How to create a Minimal, Complete, and Verifiable Example?)。这就是我们应该得到的工作。请注意,想要查看您的代码的一个原因是它让我们有机会了解您的编码水平,因此我们可以避免提出超出您理解水平的解决方案。您将需要使用一些字符串比较功能;简单地比较指针是行不通的。 OTOH,
strcmp()需要以空字符结尾的字符串。我认为您的代码不是以空值结尾的字符串。