Reputation: 75
i have string with \n, i would like to read first line of the string. i have tried following but its giving error.
String lines[] = plain.split("\\r?\\n");
String a = String.parse(lines[0]);
String b = String.parse(lines[1]);
in same time if someone tells me how to replace first line data with another value would be great.
my data is as follows
123456
A B C D
p o s j s u w
Thanks
Upvotes: 1
Views: 4284
Reputation: 687
In case you use Kotlin, you can use lines() method
val myString = "Hello \n NewLine"
myString.lines() // this will give you a List<String> type
Upvotes: 0
Reputation: 41
I think you mean to only put \n
and \r
using double back slash will give you a literal \n
"\\n" = \n
"\n" = newline
I'm also not sure about your ?
in the line
I think you want something like this (depending on the type of line endings):
String[] lines = plain.Split(new string[] {"\r\n", "\n", "\r" },StringSplitOptions.None);
After that you should probably step through your string array using for each or similar, not just assume that a you will have a [0]
and [1]
in the array.
However assuming you do have two lines accessing them will be
a = lines[0];
b = lines[1];
replacing a value would be
a = lines[0].replace("stuff","things");
Upvotes: 3
Reputation: 797
To read a line we use:
String myline = reader.readLine()
Now in your case we can use the follwoing code to read the first line however We will not use "\n" but we will look for another character like "&", "$" or even "#" and use it as below:
String mytext = "This is my code.$ I want to read the first line here.$ Please check it out";
thetext = mytext .replace("$", System.getProperty("line.separator"));
String[] strings = TextUtils.split(mytext, "$");
String a = strings[0].trim();
String b = strings[1].trim();
String a is the first line while String b is the second line
Upvotes: 1
Reputation: 143
Hope fully this will help yours..
import java.util.Arrays;
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String data = "123456\n"
+ "\n"
+ "A B C D\n"
+ "\n"
+ "p o s j s u w\n"
+ "\n"
+ "Thanks";
String[] lines = data.split("\\n");
System.out.println("Before "+Arrays.toString(lines));
lines[0]=lines[0].replace("123456","ABCD PUUJA");
System.out.println("After "+Arrays.toString(lines));
}
}
Upvotes: 1