-1

So, I have a string called proxy, it has the value of 194.156.123.1.1:8080.

How do I halve it at the colon?

So I want 2 variables like this.

IP=194.156.123.1.1
PORT=8080

I know this is really easy, but I'm new, and new people have problems that may seem easier to the experienced :)

Yuushi
  • 25,132
  • 7
  • 63
  • 81

6 Answers6

2

Use string.split:

String proxy = "194.156.123.1.1:8080";
String[] foo = string.split(":");
String ip = foo[0]; // 194.156.123.1.1
String port = foo[1]; // 8080
devnull
  • 118,548
  • 33
  • 236
  • 227
0

Can also be done Using split method on string class

upog
  • 4,965
  • 8
  • 42
  • 81
0

Try this :

String proxy = "194.156.123.1.1:8080";
String[] op = proxy.split(":"); //op[0] = "194.156.123.1.1" and
                                //op[1] = "8080"
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
0
    String s = "194.156.123.1.1:8080";
    String ip = s.split(":")[0];
    String port = s.split(":")[1];

    System.out.println(ip + ", " + port);

Split should segregate the string into string array.

Here's from the Java Doc:

public String[] split(String regex) Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result : { "boo", "and", "foo" } o { "b", "", ":and:f" } Parameters: regex - the delimiting regular expression

Returns: the array of strings computed by splitting this string around matches of the given regular expression

metsburg
  • 2,021
  • 1
  • 20
  • 32
0
$len = strlen($str);
$pos = strpose($str, ':');    

if ($pos>0 && $pos <($len-1)) {

    $ip = substr($str, 0, $pos);
    $port = substr($str, $pos+1);

} 

substr and strpos are more efficient and faster.

I have added the bound check,then it is safe.

0

You can use this.

    String proxy= "194.156.123.1.1:8080";
    System.out.println("IP: "+proxy.split(":")[0]);
    System.out.println("PORT: "+proxy.split(":")[1]);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115