Ask, ko lang po kung pano po ba mag split sa using java prog. ganito po yung regular expresion na ginamit ko para po sa split, String[] nextWords = sample.split(",|\\ |\\."); problema ko po kase kapag nag newline na saya nagiging ganito po yung output nya.
You can try getting the position of the spaces and adding "," to every space you can find. And just add the brackets at the beginning & the end.
Pseudo will be:
1. Find white space position.
2. Count all the letters before the white space.
3. Add the "," after the last letter before the white space.
AFAIK, strings in java are immutable, which means you can't break/split them. Use character arrays instead.
Pinalitan ko yung regex mo to "[,\\s\\.]+"
What this regex is:
[] does the same thing as separating tokens with *****
\s matches all whitespaces
+ means to match one or more. Placed after the square brackets, it will match one or a combination of the tokens inside (for ", " and ",\n", etc)
Using this will create an array of strings that contain only the words you're trying to split (acc. to my assumption).
-
After that it's only a matter of printing the string properly:
Code:
// there exists a better way, but you can do this if you don't know it yet
private static void printFormatted(String[] strs) {
System.out.print("[");
final int last = strs.length-1;
for (int i = 0; i < last; ++i)
System.out.printf("%s, ", strs[i]);
System.out.printf("%s]\n", strs[last]);
}
You can try getting the position of the spaces and adding "," to every space you can find. And just add the brackets at the beginning & the end.
Pseudo will be:
1. Find white space position.
2. Count all the letters before the white space.
3. Add the "," after the last letter before the white space.
AFAIK, strings in java are immutable, which means you can't break/split them. Use character arrays instead.
Pinalitan ko yung regex mo to "[,\\s\\.]+"
What this regex is:
[] does the same thing as separating tokens with *****
\s matches all whitespaces
+ means to match one or more. Placed after the square brackets, it will match one or a combination of the tokens inside (for ", " and ",\n", etc)
Using this will create an array of strings that contain only the words you're trying to split (acc. to my assumption).
-
After that it's only a matter of printing the string properly:
Code:
// there exists a better way, but you can do this if you don't know it yet
private static void printFormatted(String[] strs) {
System.out.print("[");
final int last = strs.length-1;
for (int i = 0; i < last; ++i)
System.out.printf("%s, ", strs[i]);
System.out.printf("%s]\n", strs[last]);
}
Another approach na puwede mong subukan (hindi ko ibibigay yung code, just a hint).
1) Use StringBuilder to collect the input
2) String collectedValues = StringBuilder's toString
3) Then linisin ang collectedValues (linisin I means substitute spaces, commas and periods with, for instance, "##")
4) Then use the "##" as key to split collectedValues into an array