Monday, April 15, 2024
HomeSoftware EngineeringListed Capitalization in Java | Learn to Grasp Software program Engineering, DevOps...

Listed Capitalization in Java | Learn to Grasp Software program Engineering, DevOps and Cloud

The problem#

Given a string and an array of integers representing indices, capitalize all letters on the given indices.

Instance:

• `capitalize("abcdef",[1,2,5]) = "aBCdeF"`
• `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no such thing as a index 100.

The enter can be a lowercase string with no areas and an array of digits.

Choice 1:

``````bundle resolution;

import java.util.*;

public class Resolution{
public static String capitalize(String s, int[] ind){
char[] chars = s.toCharArray();
Arrays.stream(ind)
.filter(c -> c < s.size())
.forEach(c -> chars[c] = Character.toUpperCase(chars[c]));
return new String(chars);
}
}
``````

Choice 2:

``````bundle resolution;

public class Resolution {
public static String capitalize(String s, int[] ind){
char[] outcome = s.toCharArray();

for(int i : ind) {
if(i < outcome.size) outcome[i] = Character.toUpperCase(outcome[i]);
else proceed;
}
String str = String.valueOf(outcome);
return str;

}
}
``````

Choice 3:

``````bundle resolution;

public interface Resolution {
static String capitalize(String s, int[] ind) {
for (int i : ind) {
if (i < s.size()) {
s = s.substring(0, i) + (char) (s.charAt(i) - 32) + s.substring(i + 1);
}
}
return s;
}
}
``````

Check instances to validate our resolution#

``````import java.util.Random;
import java.util.TreeSet;

import static Resolution.capitalize;

import org.junit.runners.JUnit4;
import org.junit.Check;
import static org.junit.Assert.assertEquals;

public class SolutionTest{
non-public static ultimate String lowercase = "abcdefghijklmnopqrstuvwxyz";
non-public static ultimate Random random = new Random();

@Check
public void basicTest(){
assertEquals("aBCdeF", capitalize("abcdef", new int[]{1,2,5}));
assertEquals("aBCdeF", capitalize("abcdef", new int[]{1,2,5,100}));
assertEquals("Indexinglessons", capitalize("indexinglessons", new int[]{0}));
}

non-public String solve_kvWOF(String s, int[] ind){
StringBuilder sb = new StringBuilder(s);
for(int i : ind){
if(i < sb.size())
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
}
return sb.toString();
}

@Check
public void randomTest(){
for(int i = 0; i < 100; i++){
int r = random.nextInt(10) + 10;
StringBuilder sb = new StringBuilder();
for(int j = 0; j < r; j++)
sb.append(lowercase.charAt(random.nextInt(lowercase.size())));
TreeSet<Integer> set = new TreeSet<Integer>();
for(int j = 0; j < sb.size(); j++)
int[] a = new int[set.size()];
for(int j = 0; j < a.size; j++)
a[j] = set.pollFirst();
String str = sb.toString();
assertEquals(solve_kvWOF(str, a), capitalize(str, a));
}
}
}
``````
RELATED ARTICLES