Answer the question
In order to leave comments, you need to log in
Task for strings in JAVA?
There is a task, a photo from above in English and with a translator:
And there is a solution (mine), all the tests the solution passed.
Please give feedback. How to improve the code, thanks for the feedback!
class Solution{
public static void main(String[] args) {
System.out.println(toCamelCase(""));
}
static String firstUpperCase(String word){
String[] wordArr = word.split("");
for (int i = 0; i < wordArr.length; i++){
if(i == 0){
wordArr[i] = wordArr[i].toUpperCase();
} else {
wordArr[i] = wordArr[i].toLowerCase();
}
}
StringBuilder wordString = new StringBuilder("");
for (int j = 0; j < wordArr.length; j++){
wordString.append(wordArr[j]);
}
return wordString.toString();
}
static String firstUpperCase(String word, boolean isUpperCase){
String[] wordArr = word.split("");
if(isUpperCase){
System.out.println(Character.isUpperCase(word.charAt(0)));
if( Character.isUpperCase(word.charAt(0))){
for (int i = 0; i < wordArr.length; i++){
if(i == 0){
wordArr[i] = wordArr[i].toUpperCase();
} else {
wordArr[i] = wordArr[i].toLowerCase();
}
}
} else {
for (int i = 0; i < wordArr.length; i++){
wordArr[i] = wordArr[i].toLowerCase();
}
}
}
StringBuilder wordString = new StringBuilder("");
for (int j = 0; j < wordArr.length; j++){
wordString.append(wordArr[j]);
}
return wordString.toString();
}
static String toCamelCase(String s){
if(s.equals("")) return "";
String[] strings = s.split("[-_]");
for (int i = 0; i < strings.length; i++){
if(i == 0) {
strings[i] = firstUpperCase(strings[i], true);
} else {
strings[i] = firstUpperCase(strings[i]);
}
}
StringBuilder newString = new StringBuilder("");
for (String string: strings){
newString.append(string);
}
return newString.toString();
}
}
Answer the question
In order to leave comments, you need to log in
import java.util.Arrays;
import java.util.stream.Collectors;
public class CamelCase {
public static void main(String[] args) {
System.out.println(toCamelCase("this-is-it"));
System.out.println(toCamelCase("This_is_it"));
}
static String toCamelCase(String input) {
var strings = input.split("[-_]");
return strings[0].concat(Arrays.stream(strings)
.sequential()
.skip(1)
.map(CamelCase::capitalizeFirst)
.collect(Collectors.joining()));
}
private static String capitalizeFirst(String s) {
return s.substring(0,1).toUpperCase().concat(s.substring(1));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question