我正在嘗試創建一個類Capslock,該類將接收一個字串并int[]以大寫形式回傳字符的索引。到目前為止,這是我的代碼:
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);
}
我正在努力理解如何添加u到我的int[] j. 誰能解釋一下?
uj5u.com熱心網友回復:
正如您從評論中看到的那樣,有幾種方法可以獲得所需的結果。其中一些:
方法一
- count := 大寫字母的個數
- 創建一個長度計數的陣列
- 將此陣列中的每個元素設定為對應大寫字母的索引
在代碼中:
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;
}
方法二
- 創建一個長度為 text.length() 的陣列
- 計算大寫字母,并在計算時更新陣列。
- 回傳從 0 到 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);
}
方法 3
- 串列 := 一個空串列
- 計算大寫字母,并在計算時將元素添加到串列中。
- 回傳 list.toArray()
缺點:由于 List 使用復雜型別,toArray() 使用包裝型別java.lang.Integer而不是原始型別int并回傳。也就是說,您必須將回傳型別更改為Integer[]或轉換陣列。
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]);
}
方法 4
- 使用 0 到 st.length() 范圍內的索引流
- 過濾流以僅保留那些指向 st 中大寫字符的索引。
- 從結果流中回傳一個陣列。
public static int[] allCapLocations(String st) {
return IntStream.range(0, st.length())
.filter(index -> Character.isUpperCase(st.charAt(index)))
.toArray();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/517102.html
標籤:爪哇数组索引大写
下一篇:Recyclerview選擇位置邊框會出現,未選中邊框不出現-如何在AndroidStudio中進行設計,如高亮位置
