I have a string
"Red apple, blue banana, orange".
How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :
Pattern pattern = Pattern.compile(", ");
List<Fruit> f = pattern.splitAsStream(fruitString)
.map(Fruit::valueOf)
.collect(Collectors.toList());
Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.
Use map(...)
method to perform transformations on the original String
. Instead of calling Fruit::valueOf
through a method reference, split each string on space inside map(...)
, and construct a combined string when you get exactly two parts:
List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(s -> {
String[] parts = s.split(" ");
String tmp = parts.length == 2
? parts[0]+"_"+parts[1]
: s;
return Fruit.valueOf(tmp.toUpperCase());
}).collect(Collectors.toList());
If you need to perform any additional transformations of the result, you can do them in the same lambda code block prior to the return
statement.
Your Enum
static enum Fruit {
RED_APPLE, BLUE_BANANA, ORANGE
}
Main code:
public static void main(String[] ar) throws Exception {
Pattern pattern = Pattern.compile(", ");
List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(YourClass::mapToFruit)
.collect(Collectors.toList());
System.out.println(f);
}
Helper method to offload dirty mapping part
private static Fruit mapToFruit(String input) {
String[] words = input.split("\\s");
StringBuilder sb = new StringBuilder();
if (words.length > 1) {
for (int i = 0; i < words.length - 1; i++) {
sb.append(words[i].toUpperCase());
sb.append("_");
}
sb.append(words[words.length - 1].toUpperCase());
} else {
sb.append(words[0].toUpperCase());
}
return Fruit.valueOf(sb.toString());
}
Here is another sample:
f = pattern.splitAsStream(fruitString)
.map(s -> Arrays.stream(s.split(" ")).map(String::toUpperCase).collect(Collectors.joining("_")))
.map(Fruit::valueOf).collect(Collectors.toList());
Or by StreamEx :
StreamEx.split(fruitString, ", ")
.map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
.map(Fruit::valueOf).toList();
String yourString = "Red apple, blue banana, orange";
stringArray = yourString.split(", ");
List<string> result;
//stringArray will contain 3 strings
//Red apple
//blue banana
//orange
for(string s : stringArray) {
//Replace all spaces with underscores
result.add(s.replace(" ", "_").toUpperCase());
}
To split the string you can do:
string[] output = fruitString.split(",");
You would then have to go through the string letter by letter to find spaces and replace them with strings:`
for(int i = 0; i < output.length; i++){
for(int j = 0; j < output[i].length(); j++){
char c = output[i].charAt(j);
//check for space and replace with _
}
}
then using the .toUpperCase() to conver the first char to a upper letter
Hope this helps you.
Please find the below Code, I have followed the below Steps :
1) Split the String by , first.
2) Again split the result of 1) String by " ".
3) Then if the word counts are more than 1 then only proceed to append the underscore.
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 the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} 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]);
}
}
}
References for the WordCount Method: Count words in a string method?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.