带有ip地址和端口的C#trim字符串

Ira*_*ili 0 c# string trim

可能重复:
c#中的字符串拆分

大家好我从套接字获取连接的IP地址,如下所示:>>"188.169.28.103:61635"我如何将ip地址放入一个字符串并将端口转换为另一个?谢谢.

Jon*_*eet 8

就个人而言我会用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)

另一种方法是使用正则表达式将这两个部分作为组进行匹配.老实说,我现在说这太过分了,但如果事情变得更加复杂,它可能会成为一个更具吸引力的选择.(我倾向于使用简单的字符串操作,直到事情开始变得毛茸茸并且更像"模式",此时我会突然发出正则表达式.)