2014-10-18 76 views
0

我试图实现一个正则表达式类型的程序,但只使用字母,而不是元字符,如“*”,“。”等,我是新来C,所以我努力与这个。C子串匹配

因此,例如,给定一串“cdcd”和一个搜索模式b,代码将在代码中找到b的每个实例,并用空格分隔每个实例,所以输出将会看起来像“bb”。

另一个例子是“abcbcbdbc” - 给“BC”,该方案应

匹配所有BC的输入字符串,即“一个 BCBC BD BC所以输出将是‘公元前BC’。

我已经在这几个小时,而不是试图用各种各样的任何功能,只是实现它的主要方法,并想知道是否有人可以点我正确的方向?

这是什么到目前为止,我已经实现了,作为我的代码的一部分。我将输入字符串和模式存储到数组中,并希望将输出存储到名为“match”的数组中。 :

int counter = 0; 
int j = 0; 

for (i = 0; i < stringLength; i++) 
{ 
    if (input_string[i] == search_pattern[j]) { 
     j++; } 
    else { 
     j = 0; } 
    if (j == patternLength) { 
     j = 0; 
     counter++; 
    } 
    } 



print_string("output: "); 

// used to print the substrings 

printf("%d",counter); //testing 
    int x; 
    int y; 
    if (counter > 0) { 
    for (x = 0; x < counter; x++) { 
    for (y = 0; y < patternLength; y++) { 
     print_char(search_pattern[y]); 
    } 
    if (x < counter-1) { 
     print_char('#'); 
    } 
    } 
    } 
    else { 
    print_string("No matches found"); 
    } 

但是,让输入字符串“ABCD”,当它不工作 - 给“广告”打印“广告”时,它应该打印什么

(也许是发现一个错误信息说没有匹配?)

预先感谢任何帮助:)

+0

你能给约匹配和数学阵列的更多信息? – ranifisch 2014-10-18 18:21:32

+0

你想让输出成为“我”吧? – ranifisch 2014-10-18 18:23:27

+0

我举了一些例子 - 我可以再举几个例子: 考虑字符串“hello”作为输入,而“l”作为搜索模式。我将“hello”存储在名为input的数组中,并将“l”存储在名为pattern的数组中。 input [2]和input [3] == pattern [0],所以我希望打印输入[2]和输入[3],并将它们分开一个空格,即输出为“l l”。 现在考虑“ho”作为输入,输入[0] == pattern [0],但输入[1]/= pattern [1],所以在这种情况下不应该打印任何内容,尽管h和o都处于输入字符串,它们的顺序不正确,所以“ho”不会是输出。这有意义吗? – user3186023 2014-10-18 18:25:27

回答

0
  int count = 0; 
      int pattern_index = 0; 
      for (int i = 0; i < inputLength; i++) 
      { 
       if (input[i] == patternc[pattern_index]) 
        pattern_index++; 
       else 
       { 
        pattern_index = 0; 
        if (input[i] == patternc[0] && patterncLength > 0) 
         pattern_index = 1; 
       } 
       if (pattern_index == patterncLength) 
       { 
        pattern_index = 0; 
        count++; 
       } 
      } 
+0

我在聊天中给你发消息。 – user3186023 2014-10-18 19:05:35

+0

我得到它的工作,非常感谢,非常感谢。从稍微修改它后学到了很多:) – user3186023 2014-10-18 19:15:00

+0

接受的答案将不胜感激。 – ranifisch 2014-10-18 19:17:41