Last active
June 12, 2020 09:59
-
-
Save albertofwb/39a3af71b47ca4f5879f1fe219b9f539 to your computer and use it in GitHub Desktop.
搜索父字符串中的子串,忽略父串中的空白字符
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <assert.h> | |
struct MatchOffset { | |
int start; | |
int end; | |
int GetMatchedCount() { | |
return end - start; | |
} | |
}; | |
bool IsBlankChar(const char ch) { | |
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'; | |
} | |
const char* StrstrIgnoreSubstrBlanks( | |
const char* parentStr, | |
const int parentLen, | |
const char* keyword, | |
MatchOffset* matchOffset) { | |
assert(parentStr != NULL); | |
assert(parentLen > 0); | |
assert(keyword != NULL); | |
int subLen = strnlen(keyword, parentLen); | |
assert(subLen > 0); | |
assert(matchOffset != NULL); | |
// keywords should not contains any spaces | |
const char* index = strchr(keyword, ' '); | |
assert(index == NULL); | |
int compareOffset = -1; | |
const int compareEnd = parentLen - subLen; // 最后一个可以用的下标 | |
while (compareOffset < compareEnd) { | |
compareOffset += 1; | |
int parentOffset = compareOffset; | |
int subOffset = 0; | |
while (subOffset < subLen && parentOffset < parentLen) { | |
// ignore blank characters | |
while (subOffset > 0 && | |
parentOffset < parentLen && | |
IsBlankChar(parentStr[parentOffset])) { | |
parentOffset += 1; | |
} | |
if (parentOffset >= parentLen) { | |
return NULL; | |
} | |
if (parentStr[parentOffset] == keyword[subOffset]) { | |
// 如果是最后一个字符,表示匹配成功,结束匹配循环 | |
if (subOffset == subLen - 1) { | |
matchOffset->start = compareOffset; | |
matchOffset->end = parentOffset; | |
assert(matchOffset->GetMatchedCount() > 0); | |
return parentStr + matchOffset->start; | |
} | |
// 如果不是最后一个字符, | |
// 去比较下一个字符 | |
parentOffset += 1; | |
subOffset += 1; | |
} | |
else { | |
//==== 2) 一个字符比较失败 | |
// 表示匹配失败,结束匹配循环 | |
break; | |
} | |
} | |
} | |
return NULL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment