0

Is there a way in Java in which I can split a string into an array, but with the delimiter? For example normally I would have a String such as this in the text editor I am building:

String content = "What time\nWhat day\nWhat month\n\n\nAsdf"

And if I called the split method with the \n delimiter like this:

content.split("\n")

I would get a String[] array like this:

{"What time", "What day", "What month", "Asdf"}

But I want this:

{"What time", "\n", "What day", "\n", "What month", "\n", "\n" ....}

Is there any built-in property I need to set or do I have to implement this from scratch.

Henry Zhu
  • 2,488
  • 9
  • 43
  • 87
  • Have you tried adding an extra slash in the variable? e.g. 'What time\\n' – Poriferous Jul 22 '15 at 23:47
  • 1
    http://stackoverflow.com/questions/31273020/how-to-split-a-string-while-maintaining-whitespace – Reimeus Jul 22 '15 at 23:48
  • 1
    Also http://stackoverflow.com/questions/19951850/split-string-with-regex-but-keep-delimeters-in-match-array – paisanco Jul 22 '15 at 23:48
  • 1
    [How to split a string, but also keep the delimiters?](https://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters) – Pshemo Jul 22 '15 at 23:53

1 Answers1

0

There are many ways, one of them is: "after splitting using separator, add separator after each element except last one like this":

public static void main(String[] args) {
        String content = "sawad";
        String seperator="a";
        String[] s=content.split(seperator);
        int length=s.length;
        System.out.println(length);
        for(int i=0;i<s.length;i++)
        {
            System.out.println(s[i]);
        }


        String [] d=new String[(length * 2) -1];
        for(int i=0;i<s.length;i++)
        {
            d[2*i]=s[i];
            if(i<length-1)
                d[2*(i+1) -1]=seperator;
        }

        System.out.println("------");
        System.out.println(d.length);
        for(int i=0;i<d.length;i++)
        {
            System.out.print(d[i]);
        }
    }
Safwan Hijazi
  • 2,089
  • 2
  • 17
  • 29