2015-03-19 85 views
2

我很想知道如何檢查是否字符串有兩個座標的格式,如:檢查是否字符串格式「座標/座標」

(signed int x,signed int y) 

我已經找到通過搜索一些答案但我還沒有完全得到它們(剛開始用C++),我正在尋求一個簡單的解決方案或提示如何檢查這一點。謝謝!

+0

你有沒有聽說過正則表達式? – 2015-03-19 13:12:16

+0

你可能想要正則表達式。看看一些教程,網上有很多。 – vektor 2015-03-19 13:12:26

+1

關於正則表達式,[請先閱讀本文](http://programmers.stackexchange.com/questions/223634/what-is-meant-by-now-you-have-two-problems)。如果你決定正則表達式仍然是你的問題的解決方案(很可能是,不要完全忽視它),那麼閱讀[C++中的正則表達式支持](http://en.cppreference.com/瓦特/ CPP /正則表達式)。 – 2015-03-19 13:16:26

回答

0

我會用這一個(簡單一些可能存在):

^\(\-{0,1}\d*,\-{0,1}\d*\) 

那就是:

^\(  start by a parenthesis 
\-{0,1} 0 or 1 "-" 
\d*  any digit 
,   "," 

和重複。

+0

會工作嗎?: 'if(string ==「\ d *,\ d *」)' – 2015-03-19 14:09:52

+0

@Yíu請閱讀本文[關於C++正則表達式](http://www.cplusplus.com/reference/regex/regex_match /) – 2015-03-19 14:11:55

+0

好的,感謝Link @Thomas – 2015-03-19 14:12:36

0

我假設你需要特別採取一個字符串作爲輸入。我會檢查字符串的每個值。

string str; 
// something happens to str, to make it a coordinate 
int n = 0; 
int m = 48; 
bool isANumber; 
bool hasASlash = false; 
while ((n < str.length()) and isANumber) { 
    isANumber = false; 
    if (str.at(n) == '/') { 
     hasASlash = true; // this means there is a slash somewhere in it 
    } 
    while ((m <= 57) and !isANumber) { 
     // makes sure the character is a number or slash 
     if ((str.at(n) == m) or (str.at(n) == '/')) isANumber = true; 
     m++; 
    } 
    m = 48; 
    n++; 
} 
if (hasASlash and isANumber) { 
    // the string is in the right format 
} 

請糾正我,如果我做錯了什麼......