Reputation: 285
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?
Upvotes: 0
Views: 423
Reputation: 2318
As you can read from the comments, there are several ways to get the desired results. Some of them:
Approach 1
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
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
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
public static int[] allCapLocations(String st) {
return IntStream.range(0, st.length())
.filter(index -> Character.isUpperCase(st.charAt(index)))
.toArray();
}
Upvotes: 2