user2456813
user2456813

Reputation:

java explode a line/string like php explode

I'm making a java program that would run on a local server.

Server takes request from client using PHP .

   <?php

    $file = fopen('temp.txt', 'a+');
    $a=explode(':',$_GET['content']);
    fwrite($file,$a[0].':'.$a[1]. '\n');

    fclose($file); 
    ?>

Now I have file "temp.txt" on local server.

Java Program should open the file read line by line and each like should be divided/exploded ":" (In a line there's only one ':' )

I have tried in many ways, but could not get exactly like how PHP splits the line.

Is it possible to use same/similar explode function in JAVA.

Upvotes: 9

Views: 7071

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Yes, in Java you can use the String#split(String regex) method in order to split the value of a String object.

Update: For example:

String arr = "name:password";
String[] split = arr.split(":");
System.out.println("Name = " + split[0]);
System.out.println("Password = " + split[1]);

Upvotes: 16

Mena
Mena

Reputation: 48434

You can use String.split in Java to "explode" each line with ":".

Edit

Example for a single line:

String line = "one:two:three";
String[] words = line.split(":");
for (String word: words) {
    System.out.println(word);
}

Output:

one
two
three

Upvotes: 4

Related Questions