2017-05-11 31 views
0

我正在嘗試確定我有多遠才能找到用戶輸入的搜索查詢。我試圖使用system.length的各種屬性,但我無法得到是我想要的。我基本上希望能夠輸入一組數字,並讓控制檯返回找到查詢的pi數量。分隔符是PiClass.CalculatePi只是爲了確保它不會永遠運行。發現搜索查詢之前的計數編號

Console.WriteLine("type string to search"); 

    string searchForThis = Console.ReadLine(); 

    var PiClass = new PiClass(); 
    double.TryParse(PiClass.CalculatePi(3), out double pi); 

    string piString = pi.ToString(); 

    if (piString.Contains(searchForThis) == true) 
    { 
     Console.WriteLine("Located"); 
    } 
    else 
    { 
     Console.WriteLine("Please expend search"); 
    } 

    Console.Read(); 
+1

爲什麼你需要將Pi分成'double'然後轉換回'string'?我想你想使用'string.IndexOf'函數來獲取匹配子串的第一個索引。 –

+0

PiClass.CalculatePi是做什麼用的?什麼不適用於你當前的代碼? –

+1

tryparse有未來的變化,我將需要能夠使用它在數學上作爲一個雙重的,但我也需要它在這部分字符串形式..我嘗試ge代碼來搜索一個字符串,然後告訴我搜索到的字符串之前有多少個字符。 –

回答

0

這裏亞去:

 Console.WriteLine("type string to search"); 
    string searchForThis = Console.ReadLine(); 
    var PiClass = new PiClass(); 
    double.TryParse(PiClass.CalculatePi(3), out double pi); 
    string piString = pi.ToString(); 
    int location = piString.IndexOf(searchForThis); 
    if (location >=0) 
    { 
     Console.WriteLine("Located at index: " + location.ToString()); 
    } 
    else 
    { 
     Console.WriteLine("Please expend search"); 
    } 
    Console.Read(); 
+0

測試piString.Contains在這裏並不是真的需要,我認爲indexOf將返回-1,如果它沒有找到它,所以你可以檢查是否位置> = 0 – JBdev

+0

完美工作。謝謝 –

0

正如我在評論中提及你可以使用string.IndexOf

string piString = pi.ToString(); 
int index = piString.IndexOf(searchForThis); 

if (index != -1) { 
    // There is a subsrting you are looking for. 
} 

而且index將代表來之前搜索的字符串中的字符數。