1

私のストレージ文字列は、最後の数字以外に必要なすべての数字を提供します。最後の数字には右と比較するものがないため、それはわかっています。どういうわけか、文字列の末尾に最後の数字を追加できますか?

    for(int i = 0;i < othercontent.length -1 ;i++ )
    {
        if(othercontent[i] != othercontent[i + 1])
        {
            storage = storage + othercontent[i]; 

        }
    }
4

6 に答える 6

1
for(int i = 0; i < othercontent.length ;i++ )
{
    if(i == 0 || othercontent[i] != othercontent[i - 1])
    {
        storage = storage + othercontent[i]; 
    }
}
于 2013-09-18T11:31:30.503 に答える
1

othercontent が String 配列の場合:

TreeSet<String> set = new TreeSet<>(Arrays.asList(othercontent));
othercontent = set.toArray(new String[0]);
for (String string : othercontent) {
    System.out.println(string);
}

othercontent が String の場合:

String othercontent = "ZZZZQQWEDDODRAABBNNNNO";
LinkedList<Character> list = new LinkedList<>();
for (Character character : othercontent.toCharArray()) {
    list.add(character);
}
TreeSet<Character> set = new TreeSet<>(list);
StringBuilder builder = new StringBuilder();
for (Character character : set) {
    builder.append(character);
}

System.out.println(builder.toString());

並べ替えだけでなく、重複の削除もこのコードで解決されます

出力:

ABDENOQRWZ
于 2013-09-18T11:41:06.147 に答える
0

条件をチェックする必要がないため、 for ループの外で文字列に最後の数字を追加できます

 for(int i = 0;i < othercontent.length -1; i++ ) {
    if(othercontent[i] != othercontent[i + 1]) {
        storage = storage + othercontent[i]; 
    }

}

 storage = storage + othercontent[othercontent.length - 1];
于 2013-09-18T11:30:36.017 に答える
0

重複をチェックしている場合は、ループの外側でこのようなことを行う必要があります。

if(othercontent.length>0 && storage[storage.length-1] ! = othercontent[othercontent.length-1])
{
    storage = storage+othercontent[othercontent.length-1];
}
于 2013-09-18T11:36:27.600 に答える
0

最後の要素に到達したかどうかを確認できます。

for(int i = 0;i < othercontent.length -1; i++ ) {
    if(othercontent[i] != othercontent[i + 1]) {
        storage = storage + othercontent[i]; 
    }
    //only gets executed if the last iteration is reached
    if(i==othercontent.length-2) {
        storage = storage + othercontent[i+1];
    }
}

または、条件を使用する代わりに、ループの後に次のように記述します。

storage = storage + othercontent[othercontent.length-1];
于 2013-09-18T11:27:08.620 に答える
0
for(int i = 0; i < othercontent.length -1 ; ++i )    {
    if(othercontent[i] != othercontent[i + 1]) {
        storage = storage + othercontent[i];
    }
}
if(othercontent.length>0){
    storage = storage + othercontent[othercontent.length-1];
}
于 2013-09-18T11:32:12.587 に答える