在java中操纵字符串及其字符

时间:2015-12-12 06:32:05

标签: java arrays string

public static int findFreqWithMutations(String toFind, String[] list) {
    int count = 0;
    String mutation = "";
    for (int i = 0; i < list.length; i++) {
        //if there's a mutation, let's change it!
        for (int j = 1; j < list[i].length(); j++) {
            if (list[i].charAt(j - 1) == list[i].charAt(j)) {
                mutation += "";
            } else {
                mutation += list[i].charAt(j - 1);
            }
        }
        //list[i] = mutation + list[i].charAt(list[i].length() - 1);
        mutation += list[i].charAt(list[i].length() - 1);
        list[i] = mutation;
    }
}

代码findFreqWithMutations(String to Find, String [] list)用于扫描字符串数组String[] list = {"AAA", "ABC", "CDEE", "FGHH"},并纠正突变(连续突变为相同字符,因此AAAA没有变异,CDEECDE没有变异)。

我的第三行:list[i] = mutation + list[i].charAt(list[i].length() - 1)按照应有的方式工作,

我的最后两行代码..

他们不一样吗?

1 个答案:

答案 0 :(得分:0)

我做了一些更改,结果就是你想要的:

  • 重新初始化每个字符串的变异

  • 测试Char(j + 1),然后保留

  • 最后,无所事事

    String [] list = {&#34; AAA&#34;,&#34; ABC&#34;,&#34; CDEE&#34;,&#34; FGHH&#34;};

    for (int i = 0; i < list.length; i++)
        {
        // MORE CLEAR
        String source= list[i];
        // PUT INSIDE
        String mutation = "";
    
        if (source.length()==0) continue; // if void
         mutation+=source.charAt(0);
    
        //if there's a mutation, let's change it!
        for (int j = 1; j <source.length(); j++)
            {
            if (source.charAt(j - 1) == source.charAt(j))
                mutation += "";
            else 
                mutation += source.charAt(j); // Take this, not the precedent
             }
    
        list[i] = mutation;
    }