2016-07-30 114 views
0

特定的格式爲:檢查是否匹配字符串我有一個字符串定義

char *str 

我如何檢查,以驗證是否字符串匹配的格式爲:

x-y-z 

其中,x,y和z都是int

例如:字符串1-2-4應該有效,而"1-2*3","1-2","1-2-3-4"無效。

+2

你有什麼試過自己?那是怎麼做的,或者沒有做到這一點?你的程序有什麼問題?另請[請閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask),並學習如何創建[最小,完整和可驗證示例](http:// stackoverflow .COM /幫助/ MCVE)。 –

+0

僅使用純C,還是例如正則表達式庫的一個選項? – usr2564301

+0

我認爲你應該使用正則表達式來匹配你的字符串。做一些谷歌搜索它,你會發現很多的例子約翰 – baliman

回答

0

如果您需要更多信息而不僅僅是匹配,那麼您可以使用循環遍歷字符串。我會給你一些入門代碼。

int i = 0; 
int correct = 1; 
int numberOfDashes = 0; 
while(correct && i < strlen(str)) { 
    if(isdigit(str[i])) { 

    } 
    else { 
    if(str[i] == '-') { 
     numberOfDashes++; 
    } 
    } 
    i++; 
} 
3

一個簡單的方法來實現你想要的是使用scanf()並檢查返回的值。像

ret = scanf("%d-%d-%d", &x, &y, &z); 
    if (ret == 3) {// match}; 

會做一個簡單的方法罰款。

雖然這種方法不適用於多種數據類型和較長的輸入,但只適用於固定格式。對於更復雜的場景,您可能需要考慮使用正則表達式庫。

+3

它不會爲「1-2-3-4」雖然.. – artm

+4

(也許更好的建議'sscanf'?) – usr2564301

+2

測試爲'-1- 2-3' – BLUEPIXY

0

與Sourav的答案一致。

int check(char t[]) 
{ 
    int a, b, c, d; 
    return sscanf(t, "%d-%d-%d-%d", &a, &b, &c, &d) == 3; 
} 


int main() 
{ 
    char s[] = "1-2-4"; 
    char t[] = "1-2-3-4"; 
    printf("s = %s, correct format ? %s\n", s, check(s) ? "true" : "false"); // <-- true 
    printf("t = %s, correct format ? %s\n", s, check(t) ? "true" : "false"); // <-- false 
} 
+2

測試爲'「1-2-4-」' – BLUEPIXY

0

您可以使用sscanf作爲您的特定字符串示例。

int main() 
{  
    int x,y,z; 
    char *str="1-2-4"; 
    int a = sscanf(str, "%d-%d-%d", &x, &y, &z); 
    printf("%s", (a == 3) ? "Correct format":"Incorrect format"); 

    return 0; 
} 

Demo on Ideone

sscanf格式不會爲指定的字符串工作:

int main() 
{  
    int x,y,z; 
    char *str="1-2*3"; //or "1-2" or ""1-2-3-4"" 
    int a = sscanf(str, "%d-%d-%d", &x, &y, &z); 
    printf("%s", (a == 3) ? "Correct format":"Incorrect format"); 

    return 0; 
} 

Demo on Ideone

爲了規避這一點,你需要使用regular expressions作爲t他人已經說過了。

相關問題