split it using java
i need to split and string
Sentence:NounPhrase| VerbPhrase
NounPhrase:Art| Noun
Sample:the
this should be written As
Sentence:NounPhrase
Sentence :VerbPhrase
NounPhrase:Art
NounPhrase: Noun
Sample:the
how can i do this using java
Edited
the file expression.txt
Sentence:NounPhrase VerbPhrase
NounPhrase:Art Noun
VerbPhrase:Verb|Adverb Verb
Art:the|a
Verb:jumps|sings
Noun:dog|cat
the program i used but not working
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class shift {
public static String readFileFull(String file)
{
String strLine = null;
StringBuffer sb = new StringBuffer();
try{
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
sb.append("\n");
sb.append(strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
String ret=sb.toString();
return ret;
}
public static void main(String args[]) {
String speech = readFileFul开发者_运维百科l("c://expression.txt");
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(speech);
while (sc.hasNextLine()) {
String[] ps = sc.nextLine().split(":");
for (String s : (ps[1] + "|").split("\\|"))
if (!s.equals(""))
sb.append(ps[0]+":").append(s).append("\n");
}
System.out.println(sb.toString());
}
}
and try to tell me y i am still getting error
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream("c:\\expression.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
String a[] = strLine.split(":");
String b[] = a[1].split("\\|");
for (String s1 : b) {
System.out.println(a[0] + ":" + s1.trim());
}
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Note: You will run into ArrayIndexOutOfBoundsException if your input strings do not strict to the format you mentioned...you need to take care of that case.
It's a simple logic of:
- Split the string by key value (separator is
:
)K, V
pair. - From value
V
separate it further with|
(Resulting inv
) - Foreach v in
V
: addv
in a list. Finally: - Add list of
v
's in aMap<K, List>
.
Hope this helps.
You have 3 separators line breaks
, :
and |
. so I think you should read line by line then split
twice.
精彩评论