[英]How do I check if a pattern exists in an entered string?
我有一個任務,用戶在一個函數中輸入一個字符串,然后輸入一個模式,然后必須檢查該模式是否存在於字符串中以及它出現的次數和偏移量。 我被難住了,我的同學不斷給我神秘的提示。 下面是我的獲取功能
int getNums()
{
printf("Please enter a number: "); //Initial printf
int count, patcount;
int torf;
char len_num[31]; //The character array for the initial entered string
char pat_num[6]; //The character array for the entered pattern after initial string
char *lenptr = len_num; //pointer to the address of the first element of len_num
char *patptr = pat_num; //pointer to the address of the first element of len_num
scanf("%s", len_num); //Where the user scans in their wanted number, which is treated as a string
printf("\n");
printf("%s\n", lenptr);
int len = stringLength(lenptr); //Checks how long string is
int valid = isValid(len_num); //Checks if string is valid
for(count=0; count<len_num[count]; count++) //Checks if length of string is within appropriate range
{
if(len>=10 && len<=30) //Continues to pattern get if within range
{
torf=1;
}
else //Denies continuation if string is outside of range
{
torf=0;
printf("Not within range! Try again!\n");
return (1);
}
}
printf("Please enter a pattern: "); //Initial entry statement for pattern
scanf("%s", pat_num); //User scans in pattern
printf("\n");
printf("%s\n", pat_num);
len = stringPattern(patptr); //Check how long pattern is
valid = isValid(pat_num); //Checks if pattern is valid
for(patcount=0; patcount<pat_num[patcount]; patcount++) //Checks if length of pattern is within appropriate range
{
if(len>=2 && len<=5) //Continues to pattern check if within range
{
torf=1;
}
else //Denies continuation if pattern is outside of range
{
torf=0;
printf("Pattern not within range! Try again!\n");
return (1);
}
}
checkPattern();
}
我不知道我應該如何啟動我的檢查功能。 更不用說我必須通過指針傳遞引用,而且我也堅持這樣做
既然你問的是模式匹配功能,我就沒有檢查你的字符串輸入功能。 您可以使用這個簡單的驅動程序代碼來測試我的解決方案:
#include <stdio.h>
void findPattern(char* input, char* pattern);
int main()
{
char input[31], pattern[6];
printf("Enter the string: ");
scanf("%s", input);
printf("Enter the pattern: ");
scanf("%s", pattern);
findPattern(input, pattern);
return 0;
}
我更喜歡findPattern
不是checkPattern
。 您應根據自己的方便對其重命名。 根據您的要求,除了stdio.h
庫函數之外,我沒有使用任何庫函數。 以下是我對這項任務的看法,我已經在評論中解釋了邏輯。 基本上,它只是遍歷整個輸入字符串一次,它檢查與模式中的初始字符是否匹配。 如果是這樣,它會標記偏移量並進一步向下搜索模式以找到完整的匹配項。
void findPattern(char* input, char* pattern)
{
int i = 0; // iterator for input
int j = 0; // iterator for pattern
// solution variables
int offset = 0;
int occurrence = 0;
// Search the entire input string
while (input[i] != '\0')
{
// Mark the offset whenever the first character of the pattern matches
if (input[i] == pattern[j])
{
offset = i;
// I didn't quite get the relativity of your offset
// Maybe you need: offset = i + 1;
}
// Search for complete pattern match
while (input[i] != '\0' && pattern[j] == input[i])
{
// Go for the next character in the pattern
++j;
// The pattern matched successfully if the entire pattern was searched
if (pattern[j] == '\0')
{
// Display the offset
printf("\nPattern found at offset %d", offset);
// Increment the occurrence
++occurrence;
// There are no more characters left in the pattern
break;
}
else
{
// Go for the next character in the input
// only if there are more characters left to be searched in the pattern
++i;
}
}
// Reset the pattern iterator to search for a new match
j = 0;
// Increment the input iterator to search further down the string
++i;
}
// Display the occurrence of the pattern in the input string
printf("\nThe pattern has occurred %d times in the given string", occurrence);
}
我必須通過指針傳遞引用,而且我也堅持這樣做
如果是這種情況,那么代替findPattern(input, pattern);
,調用這個函數為:
findPattern(&input, &pattern);
你可能想太多了。 您有一個包含多個字符的字符串input
,您想計算其中pattern
的多字符匹配的數量。關於字符串的一個好處是您不需要知道它們需要迭代多長時間,因為根據定義C 中的字符串以空終止字符結尾。
這允許您簡單地在findpattern
函數中保留一個索引,並且每次input
中的字符與pattern
中的字符匹配時都會增加索引(否則您將索引歸零)。 如果您達到pattern[index] == '\\0'
的點,則您已匹配模式中的所有字符。
您必須始終聲明一個具有類型的函數,該類型將提供有意義的返回,以指示該函數執行的任何操作的成功/失敗,如果它對您的代碼的其余部分是必要的(如果該函數只是打印輸出 - 那么void
很好)。
否則,您需要選擇一個合理的返回類型來指示是否(以及有多少)在input
中找到了pattern
匹配項。 這里一個簡單的int
類型就可以了。 (這將可以返回的匹配數量限制為2147483647
,這應該2147483647
)。
將這些部分放在一起,您可以將您的功能簡化為類似於:
int findpattern (const char *input, const char *ptrn)
{
int n = 0, idx = 0; /* match count and pattern index */
while (*input) { /* loop over each char in s */
if (*input == ptrn[idx]) /* if current matches pattern char */
idx++; /* increment pattern index */
else /* otherwize */
idx = 0; /* zero pattern index */
if (!ptrn[idx]) { /* if end of pattern - match found */
n++; /* increment match count */
idx = 0; /* zero index for next match */
}
input++; /* increment pointer */
}
return n; /* return match count */
}
添加一個簡短的示例程序,允許您輸入pattern
並input
作為程序的前兩個參數(如果未提供一個或兩個,則使用顯示的默認值):
int main (int argc, char **argv) {
char *pattern = argc > 1 ? argv[1] : "my",
*input = argc > 2 ? argv[2] : "my dog has fleas, my cat has none";
int n;
if ((n = findpattern (input, pattern)))
printf ("'%s' occurs %d time(s) in '%s'\n", pattern, n, input);
else
puts ("pattern not found");
}
請注意提供有意義的返回如何允許您 (1)驗證是否找到匹配項; (2) 提供通過返回找到的匹配數。 完整的代碼只需要標題stdio.h
,例如
#include <stdio.h>
int findpattern (const char *input, const char *ptrn)
{
int n = 0, idx = 0; /* match count and pattern index */
while (*input) { /* loop over each char in s */
if (*input == ptrn[idx]) /* if current matches pattern char */
idx++; /* increment pattern index */
else /* otherwize */
idx = 0; /* zero pattern index */
if (!ptrn[idx]) { /* if end of pattern - match found */
n++; /* increment match count */
idx = 0; /* zero index for next match */
}
input++; /* increment pointer */
}
return n; /* return match count */
}
int main (int argc, char **argv) {
char *pattern = argc > 1 ? argv[1] : "my",
*input = argc > 2 ? argv[2] : "my dog has fleas, my cat has none";
int n;
if ((n = findpattern (input, pattern)))
printf ("'%s' occurs %d time(s) in '%s'\n", pattern, n, input);
else
puts ("pattern not found");
}
示例使用/輸出
檢查多個匹配項:
$ ./bin/findpattern
'my' occurs 2 time(s) in 'my dog has fleas, my cat has none'
單場比賽:
$ ./bin/findpattern fleas
'fleas' occurs 1 time(s) in 'my dog has fleas, my cat has none'
未找到圖案
$ ./bin/findpattern gophers
pattern not found
所有相同的模式:
$ ./bin/findpattern my "mymymy"
'my' occurs 3 time(s) in 'mymymy'
函數本身的輸出
雖然最好提供一個返回值來指示匹配的數量(這將允許以多種不同方式重用該函數),但如果您只是想讓它成為每次輸出結果的輸出函數被調用,然后簡單地輸出移動到功能和聲明另一個指針input
,以便input
被保存在最后打印。
變化很小,例如
#include <stdio.h>
void findpattern (const char *input, const char *ptrn)
{
const char *p = input; /* pointer to input */
int n = 0, idx = 0; /* match count and pattern index */
while (*p) { /* loop over each char in s */
if (*p == ptrn[idx]) /* if current matches pattern char */
idx++; /* increment pattern index */
else /* otherwize */
idx = 0; /* zero pattern index */
if (!ptrn[idx]) { /* if end of pattern - match found */
n++; /* increment match count */
idx = 0; /* zero index for next match */
}
p++; /* increment pointer */
}
if (n) /* output results */
printf ("'%s' occurs %d time(s) in '%s'\n", ptrn, n, input);
else
puts ("pattern not found");
}
int main (int argc, char **argv) {
char *pattern = argc > 1 ? argv[1] : "my",
*input = argc > 2 ? argv[2] : "my dog has fleas, my cat has none";
findpattern (input, pattern);
}
(使用和輸出同上)
仔細檢查一下,如果您還有其他問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.