就个人而言我会用Substring:
int colonIndex = text.IndexOf(':');
if (colonIndex == -1)
{
// Or whatever
throw new ArgumentException("Invalid host:port format");
}
string host = text.Substring(0, colonIndex);
string port = text.Substring(colonIndex + 1);
Run Code Online (Sandbox Code Playgroud)
Mark提到使用string.Split哪个也是一个不错的选择 - 但是你应该检查部件的数量:
string[] parts = s.Split(':');
if (parts.Length != 2)
{
// Could be just one part, or more than 2...
// throw an exception or whatever
}
string host = parts[0];
string port = parts[1];
Run Code Online (Sandbox Code Playgroud)
或者,如果您对包含冒号的端口部分感到满意(就像我的Substring版本那样),那么您可以使用:
// Split into at most two parts
string[] parts = s.Split(new char[] {':'}, 2);
if (parts.Length != 2)
{
// This time it means there's no colon at all
// throw an exception or whatever
}
string host = parts[0];
string port = parts[1];
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用正则表达式将这两个部分作为组进行匹配.老实说,我现在说这太过分了,但如果事情变得更加复杂,它可能会成为一个更具吸引力的选择.(我倾向于使用简单的字符串操作,直到事情开始变得毛茸茸并且更像"模式",此时我会突然发出正则表达式.)