I am doing the following programming exercise: The old switcheroo. The statement is:
Write a function
Kata.Vowel2Index("this is my string") == "th3s 6s my str15ng"
Kata.Vowel2Index("Codewars is the best site in the world") == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld"
Your function should be case insensitive to the vowels.
I have doubts when the input is an empty string, I mean when we test with:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class KataTest {
@Test public void test4() {
assertEquals("", Kata.vowel2Index(""));
}
}
My question is, why if we use contains, we have to check if input string is empty?
import java.util.*;
public class Kata {
static final String VOWELS = "AEIOUaeiou";
public static String vowel2Index/*🔡➡️👆*/(String s) {
if(s==null || s.equals("")) return "";
String[] letters = s.split("");
for(int i = 0; i < letters.length; i++){
if(VOWELS.contains(letters[i])){
letters[i] = String.valueOf(i+1);
}
}
return String.join("",letters);
}
}
Or check if the current string inside the loop is empty:
import java.util.*;
public class Kata {
static final String VOWELS = "AEIOUaeiou";
public static String vowel2Index/*🔡➡️👆*/(String s) {
String[] letters = s.split("");
for(int i = 0; i < letters.length; i++){
if(letters[i] != "" && VOWELS.contains(letters[i])){
letters[i] = String.valueOf(i+1);
}
}
return String.join("",letters);
}
}
But we can omit the previous condition when we use indexOf:
import java.util.*;
public class Kata {
static final String VOWELS = "AEIOUaeiou";
public static String vowel2Index/*🔡➡️👆*/(String s) {
String[] letters = s.split("");
for(int i = 0; i < letters.length; i++){
if(VOWELS.indexOf(letters[i]) > 0){
letters[i] = String.valueOf(i+1);
}
}
return String.join("",letters);
}
}
I have also read:
- How to check if a String contains another String in a case insensitive manner in Java?
- Java indexOf method for multiple matches in String
What are the differences between contains and indexOf?‽?
Aucun commentaire:
Enregistrer un commentaire