-4

This is my code so far. That's how I would break up the String by "|". Now I would like to know how would I go about storing each part.

public class Address {
private String lines;

public Address(String lines)
{
    this.lines = lines;
    String[] arrOfStr = this.lines.split("|");
}

This constructor should accept an address in parts separated by "|" The constructor will then need to break the String into parts and then store each part part1|part2|part3

  • Do you have a question? If so stick it in and change the title accordingly. –  Mar 12 '20 at 08:11
  • What exactly is the problem here? Storing the array itself would be similar to what you're doing with `lines`. If the parts should have named variables then create those and assign the respective array elements. – Thomas Mar 12 '20 at 08:12
  • You already heave those values as arrOfStr[0],arrOfStr[1] try to print it or set to variables. – Hemant Metalia Mar 12 '20 at 08:12
  • 4
    Keep in mind that `.split` takes a **regular expression**. The `|` character is part of the regex syntax. Replace with `\\|` so that it is escaped and treated as a literal `|` character. – npinti Mar 12 '20 at 08:12
  • Could be a duplicate of [Splitting a Java String by the pipe symbol using split(“|”)](https://stackoverflow.com/questions/10796160/splitting-a-java-string-by-the-pipe-symbol-using-split) and [Splitting string with pipe character (“|”)](https://stackoverflow.com/questions/21524642/splitting-string-with-pipe-character), but it is hard to say what exactly you are asking here. – Ivar Mar 12 '20 at 08:16

2 Answers2

5

well for a start you need to split using \\| and then you need to store the result in a field

// field

String[] arrOfStr

public Address(String lines)
{
    this.lines = lines;
    arrOfStr = this.lines.split("\\|");
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0
public class Address {
    private String parts[];

    public Address(String lines) {
        parts = lines.split("\\|");
    }

    public void printAddress() {
        for (String p : parts) {
            System.out.println(p);
        }
    }

    public static void main(String[] args) {
        Address address = new Address("House No. 1|Main Street|City|Country");
        address.printAddress();
    }
}
Dinesh Shekhawat
  • 504
  • 6
  • 13