将字符数组的子字符串与C中的另一个字符数组进行比较

标签 c arrays string substring pi

我有两个名为 arraypiarraye 的字符数组,其中包含我从文件中读取的数字。每个都有 1,000,000 个字符。我需要从 arraye 中的第一个字符开始(在本例中为 7)并在 arraypi 中搜索它。如果 arraypi 中存在 7,那么我必须搜索 arraye 的下一个子字符串(在本例中为 71)。然后搜索7187182等,直到arraypi中不存在该子串。然后我必须简单地将最大子字符串的长度放在一个整数变量中并打印出来。

值得一提的是,arraypi 每 50 个字符包含一个换行符,而 arraye 每 80 个字符包含一个换行符,尽管我认为这不会成为问题吧?

我尝试考虑一种方法来实现这一点,但到目前为止我还没有想到什么。

最佳答案

我不确定我是否做对了。我有这样的想法:

  • 假设我们有整个 arraypi 在浏览器中
  • 您使用组合键 ctrl+f 进行查找
  • 开始逐个字母地输入 arraye 的内容,直到看到红色的不匹配
  • 您想要到那时您能够输入的字符数

如果这是正确的,那么像下面这样的算法应该可以解决问题:

#include <stdio.h>
#define iswhitespace(X) ((X) == '\n' || (X) == ' ' || (X) == '\t')

int main( ) {

    char e[1000] = "somet\n\nhing";
    char pi[1000] = "some other t\nhing\t som\neth\n\ning";

    int longestlen = 0;
    int longestx = 0;
    int pix = 0;
    int ex = 0;
    int piwhitespace = 0;       // <-- added
    int ewhitespace = 0;        // <-- these

    while ( pix + ex + piwhitespace < 1000 ) {

        // added the following 4 lines to make it whitespace insensitive
        while ( iswhitespace(e[ex + ewhitespace]) )
            ewhitespace++;
        while ( iswhitespace(pi[pix + ex + piwhitespace]) )
            piwhitespace++;

        if ( e[ex + ewhitespace] != '\0' && pi[pix + ex + piwhitespace] != '\0' && pi[pix + ex + piwhitespace] == e[ex + ewhitespace] ) {
            // the following 4 lines are for obtaining correct longestx value
            if ( ex == 0 ) {
                pix += piwhitespace;
                piwhitespace = 0;
            }
            ex++;
        }
        else {
            if ( ex > longestlen ) {
                longestlen = ex;
                longestx = pix;
            }
            pix += piwhitespace + 1;
            piwhitespace = 0;
            // the two lines above could be replaced with
            // pix++;
            // and it would work just fine, the injection is unnecessary here
            ex = 0;
            ewhitespace = 0;
        }
    }

    printf( "Longest sqn is %d chars long starting at %d", longestlen, longestx + 1 );

    putchar( 10 );
    return 0;
}

发生的事情是,循环首先搜索匹配的起点。在找到匹配之前,它会增加正在检查的数组的索引。当它找到一个起点时,它就会开始递增包含搜索词的数组的索引,同时保持另一个索引不变。

直到下一次不匹配,即进行记录检查时,搜索词索引将被重置,考生索引将再次开始递增。

我希望这能以某种方式有所帮助,希望比解决这一单一时间的斗争更有帮助。

编辑:

更改代码以忽略空白字符。

关于将字符数组的子字符串与C中的另一个字符数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24158482/

相关文章:

jquery - 使用 jquery 从数组列表中添加和删除数组项

c - 将变量传递给 pthread_create 函数

c - scanf 中的可选输入变量

c - 如何更改作为参数传递的变量的值?

C编程中检查输入是否为数字

java - 测试排序数组方法

Swift:字符串 - 计算高度的第一个字符位置?

mysql - 使用 MySQL 函数将字符串的第一个字符移动到字符串的末尾

c - 向量化嵌套索引

javascript - 使用 Jquery 将空格替换为 "&nbsp;"