Reputation: 1022
I have a long string which holds the tags p /p for paragraphs. This is html string to be placed in web view.
I need to split the paragraphs into two and assign each one to a string. Example:
String A:
<p> I have an orange <\p>
<p> I have an apple <\p>
<p> I have a banana <\p>
<p> I have a fruit <\p>
<p> I love to go bike riding<\p>
<p> Hello how are you <\p>
Now I need to split the paragraphs into 2 and assign to 2 different strings:
String B should have:
<p> I have an orange <\p>
<p> I have an apple <\p>
<p> I have a banana <\p>
String C should have:
<p> I have a fruit <\p>
<p> I love to go bike riding<\p>
<p> Hello how are you <\p>
how can I achieve it?
Upvotes: 1
Views: 1482
Reputation: 2738
I just assume you mean </p>
instead of <\p>
as the closing tag.
Assuming you always have this structure, with <p>...</p>
following <p>...</p>
and nothing inbetween, you can just do this:
String A = "<p> I have an orange </p>"
+ "<p> I have an apple </p>"
+ "<p> I have a banana </p>"
+ "<p> I have a fruit </p>"
+ "<p> I love to go bike riding</p>"
+ "<p> Hello how are you </p>";
String[] paragraphs = A.split("</p>");
final int halfParagraphs = (int) Math.ceil((double) paragraphs.length / 2);
StringBuilder bBuilder = new StringBuilder();
StringBuilder cBuilder = new StringBuilder();
for(int idxB = 0; idxB < halfParagraphs; idxB++) {
int idxC = idxB + halfParagraphs;
// split removes the separator, so we need to append it again
bBuilder.append(paragraphs[idxB]).append("</p>");
if (paragraphs.length > idxC) {
cBuilder.append(paragraphs[idxC]).append("</p>");
}
}
String B = bBuilder.toString();
String C = cBuilder.toString();
I also assumed you want String B to hold more values if the number cannot be evenly distributed. This is certainly not the cleanest solution, but it works without adding an extra character in the Text.
Upvotes: 0
Reputation: 38098
This is the code. Note where I added the § character in strA, in order to split the string:
final String strA = "<p> I have an orange </p><p> I have an apple </p><p> I have a banana </p>§<p> I have a fruit </p><p> I love to go bike riding</p><p> Hello how are you </p>";
final String arr[] = strA.split("§");
final String strB = arr[0]; // Contains: "<p> I have an orange </p><p> I have an apple </p><p> I have a banana </p>"
final String strC = arr[1]; // Contains: "<p> I have a fruit </p><p> I love to go bike riding</p><p> Hello how are you </p>"
Upvotes: 1