2017-04-20 195 views
-3

我有一個字符串像----->「12:13:0 james,1324,7656119796027」 我想在我的程序中輸入james並獲得1234.你能幫我嗎那?謝謝。查找另一個字符串後的字符串

+1

你的意思'1324' - 「我要進入** **詹姆斯,讓** ** 1234」? –

+2

你最好給出更多可以代表所有可能的輸入和輸出參數的例子。 –

+3

這似乎並不困難。看看[String.Contains](https://msdn.microsoft.com/en-us/library/dy85x1sa(v = vs.110).aspx),[String.IndexOf](https:// msdn。 microsoft.com/en-us/library/system.string.indexof(v=vs.110).aspx),[String.Substring](https://msdn.microsoft.com/en-us/library/system。 string.substring(v = vs.110).aspx)... – Pikoh

回答

0

您可以使用string.IndexOf()來查找輸入的索引。就像這樣:

string str = "12:13:0 james,1324,7656119796027"; 
string key = "james"; 

int index = str.IndexOf(key); 
string stringAfterKey= str.Substring(index + key.Length + 1/*,*/); 

string stringYouNeed = stringAfterKey.Split(new char[] { ',' })[0]; // Get 1324, then sort it 

但請考慮可能有多個與您的關鍵字匹配的索引。你最好讓你的輸入&輸出更清晰。

+0

非常感謝。欣賞它。 – mreroxter

0

假設你總是希望逗號後的第一個結果你輸入後:

private readonly string[] Separators = new string[] { "," }; 

public void YourMethod() 
{ 
    string result = FindSubstring("james"); 
    Console.WriteLine(result); 
} 

private string FindSubstring(string input) 
{ 
    string source = "12:13:0 james,1324,7656119796027"; 
    int first = source.IndexOf(input) + input.Length; 
    string substring = source.Substring(first); 

    string[] splittedSubstring = substring.Split(Separators, StringSplitOptions.RemoveEmptyEntries); 
    return splittedSubstring[0]; 
} 
相關問題