C# trim string with ip address and port [duplicate]
Possible Dup开发者_如何学运维licate:
string split in c#
Hello guys i am getting connected ip address from socket which is looks like this: >> "188.169.28.103:61635" how i can put ip address into one string and port into another? Thanks.
Personally I'd use 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);
Mark mentioned using string.Split
which is a good option too - but then you should probably check the number of parts:
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];
Or if you're happy with the port part containing a colon (as my Substring
version does) then you can use:
// 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];
Another alternative would be to use a regular expression to match the two parts as groups. To be honest I'd say that's overkill at the moment, but if things became more complicated it may become a more attractive option. (I tend to use simple string operations until things start getting hairy and more "pattern-like", at which point I break out regular expressions with some trepidation.)
I would use string.Split()
:
var parts = ip.Split(':');
string ipAddress = parts[0];
string port = parts[1];
Try String.Split
:
string[] parts = s.Split(':');
This will put the IP address in parts[0]
and the port in parts[1]
.
string test = "188.169.28.103:61635";
string [] result = test.Split(new char[]{':'});
string ip = result[0];
string port = result[1];
精彩评论