Please find the code below, I followed these steps:
1) First split the line.
2) Divide the result again 1) String by "".
3) Then, if the number of words is more than 1, then go on to add underlining.
Demo:
http://rextester.com/NNDF87070
import java.util.*;
import java.lang.*;
class Rextester
{
public static int WordCount(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
public static void main(String args[])
{
String cord = "Red apple , blue banana, orange";
String[] parts = cord.split(",");
String[] result1 = new String[parts.length];
for(int i=0; i<parts.length;i++) {
String[] part2 = parts[i].split(" ");
if(parts[i].length() > 1 && WordCount(parts[i]) > 1)
{
String result = "_";
String uscore = "_";
for(int z =0; z < part2.length; z++)
{
if(part2.length > 1 ) {
if (z + 1 < part2.length) {
result = part2[z] + uscore + part2[z + 1];
}
}
}
result1[i] = result.toUpperCase();
}
else
{
result1[i] = parts[i];
}
}
for(int j =0 ; j <parts.length; j++)
{
System.out.println(result1[j]);
}
}
}
Links for the WordCount method: Read words in a string method?
source
share