My string variable contains a String, each on a different line. How do I find the number of new lines in it, and then each word separated by a ,
delimiter on a particular string line? The variable content is something like below
null37,Abhishek,ARS,b,ABC,Development,2011-05-30 00:00:00.0,abhishek123@cjb.net
null38,Abhishek,SAS,c,ABC,Development,2011-05-30 00:00:00.0,abhishek1开发者_JAVA技巧23@cjb.net
null39,Abhishek,DGV,a,ABC,Production,2011-05-30 00:00:00.0,abhishek123@cjb.net
Edited:
I tried this
String xmlstr="""null37,Abhishek,ARS,b,ABC,Development,2011-05-30 00:00:00.0,abhishek123@cjb.net
null38,Abhishek,SAS,c,ABC,Development,2011-05-30 00:00:00.0,abhishek123@cjb.net
null39,Abhishek,DGV,a,ABC,Production,2011-05-30 00:00:00.0,abhishek123@cjb.net"""
String[] splitStr = xmlstr.split('\n');
for(String str : splitStr)
{
String splitted = str.split(',');
println splitted
}
I am getting something unknown,
[Ljava.lang.String;@148bd3
[Ljava.lang.String;@a4e743
[Ljava.lang.String;@4aeb52
To get the number of newlines do
int newLines = myString.split("\\r?\\n").length;
To get each word separated by a comma do
String[] words = myString.split(",");
You could also use Groovy's splitEachLine
method.
It works like this:
String xmlstr = """null37,Abhishek,ARS,b,ABC,Development,2011-05-30 00:00:00.0,abhishek123@cjb.net
null38,Abhishek,SAS,c,ABC,Development,2011-05-30 00:00:00.0,abhishek123@cjb.net
null39,Abhishek,DGV,a,ABC,Production,2011-05-30 00:00:00.0,abhishek123@cjb.net"""
xmlstr.splitEachLine( /,/ ) { tokens ->
println "${tokens[1]} : ${tokens[7]}"
}
That prints out:
Abhishek : abhishek123@cjb.net
Abhishek : abhishek123@cjb.net
Abhishek : abhishek123@cjb.net
Your mistake was only that
String splitted = str.split(','); // Wrong
should have been an array:
String[] splitted = str.split(','); // Fixed
When a Java program prints arrays, the first character is L
followed by the class, and then the object's memory location.
Here's some Java code that will compile so you can see the problem that scripting languages hide:
String[] lines = originalString.split("\\r?\\n")); // Do this only once
int numberOfNewLines = lines.length;
int myLine = 5; // Say
String[] words = lines[myLine];
You could easily wrap these idea up in some clean code.
new line char is '\n'. so you should first split by '\n' . then split by ',' .
String[] splittedByNewLine = originalString.Split('\n');
for(String str : splittedByNewLine )
{
String[] splittedByComma = str.split(',');
for(String str : splittedByComma )
{
"println str..."
}
}
精彩评论