該程式的想法是它從掃描儀中獲取除以空間的文本。
我需要撰寫一個方法來從文本創建一個陣列,洗掉重復項并回傳一個只使用一次且沒有重復項的單詞陣列。
我不知道如何制作一組新的獨特單詞。只使用簡單和基本的構造,沒有HashSet等*
例如:
a b a b c a b d
結果:
c d
public static String Dublicate(String text) {
String[] dublic = text.split(" ");
String result="";
for (int i = 0; i < dublic.length; i ) {
for (int j = i 1; j < dublic.length; j )
if (dublic[i].equals(dublic[j]))
dublic[j] = "delete";
}
for (String s: dublic) {
if (s !="delete") {
result =result s " ";
}
}
return result;
}
uj5u.com熱心網友回復:
按空間分割
對于按空格分割,我們可以使用split()方法并可以在引數中傳遞空格字串 ( "" )。
String[] texts = text.split(" ");
洗掉重復元素
如果我們可以使用 java 1.8 或大于 1.8,我們可以使用流 API 來獲取不同的元素,例如。
Arrays.stream(texts).distinct().toArray(String[]::new);
或者,如果我們需要使用 java 1.7 來實作它,我們可以使用 HashSet 來獲取不同的元素,例如。
String[] distinctElements = new HashSet<String>(Arrays.asList(texts)).toArray(new String[0]);
最終的源代碼可以是這樣的:
public static String[] textToArray1_7(String text) {
//split by space
String[] texts = text.split(" ");
//Distinct value
return Arrays.stream(texts).distinct().toArray(String[]::new);
}
public static String[] textToArray1_8(String text) {
//split by space
String[] texts = text.split(" ");
//Distinct value
return new HashSet<String>(Arrays.asList(texts)).toArray(new String[0]);
}
如果有任何進一步的問題,可以要求更多的澄清。
uj5u.com熱心網友回復:
您忘記將第 i 個元素標記為重復,以防萬一。在下面的代碼中查看我的評論
public static String Dublicate(String text) {
String[] dublic = text.split(" ");
String result="";
for (int i=0; i<dublic.length; i ){
if (dublic[i].equals("delete")) { // Minor optimization:
// skip elements that are already marked
continue;
}
boolean isDub = false; // we need to track i-th element
for(int j=i 1; j<dublic.length; j ) {
if (dublic[i].equals(dublic[j])) {
dublic[j] = "delete";
isDub = true; // i-th element is also a duplicate...
}
}
if (isDub) {
dublic[i] = "delete"; // ...so you should also mark it
}
}
for(String s: dublic){
if(!s.equals("delete")) { // for strings you should use "!equals" instead of "!="
result = result s " ";
}
}
return result;
}
PS如果原始文本包含“洗掉”結果將不正確,因為您使用“洗掉”作為保留標記詞
uj5u.com熱心網友回復:
如果需要回傳唯一字串陣列,則必須壓縮輸入拆分后的初始字串陣列以排除無效值,并且需要回傳較小的副本:
public static String[] uniques(String text) {
String[] words = text.split(" ");
int p = 0; // index/counter of unique elements
for (int i = 0; i < words.length; i ) {
String curr = words[i];
if (null == curr) {
continue;
}
boolean dupFound = false;
for (int j = i 1; j < words.length; j ) {
if (null == words[j]) {
continue;
}
if (curr.equals(words[j])) {
words[j] = null;
dupFound = true;
}
}
if (dupFound) {
words[i] = null;
} else {
words[p ] = words[i]; // shift unique elements to the start of array
}
}
return Arrays.copyOf(words, p);
}
如果回傳唯一字串陣列,則可以String::join在測驗中使用如下所示方便地將其轉換為字串。測驗:
System.out.println(Arrays.toString(uniques("a b a b c a b d")));
System.out.println(String.join(" ", uniques("a b a b c a b d")));
輸出
[c, d]
c d
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383174.html
