I'm trying to create a class Capslock
which will take in a string and return an int[]
of the indexes of the character in uppercase. Here is my code so far:
public class Capslock {
public static int[] allCapLocations(String st) {
int count = 0;
for (int x = 0; x < st.length(); x ) {
if (Character.isUpperCase(x)) {
count ;
}
}
int[] j = new int[count];
for (int u = 0; u < st.length(); u ) {
if (Character.isUpperCase(u)) {
j.add(u);
}
I'm struggling to understand how to add u
into my int[] j
. Can anyone please explain?
CodePudding user response:
As you can read from the comments, there are several ways to get the desired results. Some of them:
Approach 1
- count := count of the uppercase letters
- Create an array of length count
- Set each element in this array to the index of the corresponding uppercase letter
In code:
public static int[] allCapLocations(String st) {
int count = 0;
for (int i = 0; i < st.length(); i ) {
char ch = st.charAt(i);
if (Character.isUpperCase(ch)) {
count ;
}
}
int[] uppercaseIndices = new int[count];
int cursor = 0;
for (int index = 0; index < st.length(); index ) {
char ch = st.charAt(index);
if (Character.isUpperCase(ch)) {
uppercaseIndices[cursor] = index;
cursor ;
}
}
return uppercaseIndices;
}
Approach 2
- Create an array of length text.length()
- Count the uppercase letters, and while counting, update the array.
- Return a copy of the partial array ranging from 0 to count - 1.
public static int[] allCapLocations(String st) {
int[] uppercaseIndices = new int[st.length()];
int count = 0;
for (int index = 0; index < st.length(); index ) {
char ch = st.charAt(index);
if (Character.isUpperCase(ch)) {
uppercaseIndices[count] = index;
count ;
}
}
return java.util.Arrays.copyOfRange(uppercaseIndices, 0, count);
}
Approach 3
- list := an empty List
- Count the uppercase letters, and while counting, add elements to list.
- Return list.toArray()
Drawback: as List uses complex types, the wrapper type java.lang.Integer
instead of the primitive type int
is used and returned by toArray(). That is, you have to either change the return type to Integer[]
or convert the array.
public static Integer[] allCapLocations(String st) {
List<Integer> uppercaseIndices = new ArrayList<>();
for (int index = 0; index < st.length(); index ) {
char ch = st.charAt(index);
if (Character.isUpperCase(ch)) {
uppercaseIndices.add(index);
}
}
return uppercaseIndices.toArray(new Integer[0]);
}
Approach 4
- Use a stream of indices in the range between 0 and st.length()
- Filter the stream to retain only those indices that point to an uppercase character in st.
- Return an array from the resulting stream.
public static int[] allCapLocations(String st) {
return IntStream.range(0, st.length())
.filter(index -> Character.isUpperCase(st.charAt(index)))
.toArray();
}