-2

String is Like This:

String Text="Bank name Some Thing \n Reminder is Some Thing \n Date Some";

I want it to be Like this:

String T1="Bank Name Some Thing";
String T2="Reminder is Some Thing";
String T3="Date Some";

I'm Working with java I will be thankful to Your Help.

jdaz
  • 5,964
  • 2
  • 22
  • 34
ebrahim EH
  • 21
  • 4

2 Answers2

0

You can use split() function to split the sentences based on delimiter \n and store them in an array. Then by iterating the array, you can access each string:

public static void main(String[] args) {
    String Text="Bank name Some Thing \n Reminder is Some Thing \n Date Some";

    String[] sentences = Text.split("\n");

    for (String s : sentences){
        System.out.println(s.trim());
    }
}

Related method's doc page is here.

Since there are additional spaces around delimiter, you can use trim method to remove them.

If you want to assign the values to different variables as mentioned in your question, you can do it as follows:

String T1 = sentences[0].trim();
String T2 = sentences[1].trim();
String T3 = sentences[3].trim();

You should also follow Java naming conventions e.g. the name of the variables should be t1, t2, and t3 instead of T1, T2, and T3.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Sercan
  • 2,081
  • 2
  • 10
  • 23
0

Another option is to use the Scanner

String text =
        "Bank name Some Thing \n Reminder is Some Thing \n Date Some";
Scanner scan = new Scanner(text);

while (scan.hasNextLine()) {
    System.out.println(scan.nextLine().trim());
}

Prints

Bank name Some Thing
Reminder is Some Thing
Date Some

If you know how many lines you have you can just assign them directly as follows:

String T1=scan.nextLine().trim();
String T2=scan.nextLine().trim();
String T3=scan.nextLine().trim();
WJS
  • 36,363
  • 4
  • 24
  • 39