删除数组中最后一次出现的元素

时间:2015-12-13 05:14:15

标签: java arrays

如果数组的一行包含字符:

line = "I appreciate you helping me out!"

假设我想删除字母'e'的最后一个字母。 怎么样? 即结果应为:

"I appreciate you helping m out!"

这是我的想法,我知道语法错误。我从26开始,因为这是最后一次'e'位置发生在字符串的长度上。

for (int i = 26; i < line.length() ; i++)
    line.chars('e') = (line.chars('') && line.chars(i));
}

4 个答案:

答案 0 :(得分:3)

String line = "I appreciate you helping me out!";
int index = line.lastIndexOf('e');
if(index != -1) //prevent IndexOutOfBoundsException in case it can't find the char
    line = new StringBuilder(line).deleteCharAt(index).toString();

String line = "I appreciate you helping me out!";
for (int i = line.length(); --i >= 0;){
    if(line.charAt(i) == 'e'){
        line = line.substring(0, i) + line.substring(i + 1);
        break;
    }
}

答案 1 :(得分:0)

或者你可以使用如下的正则表达式:

String word = "I appreciate you helping me out!";
System.out.println(word.replaceAll("[e]([^e]*)$","$1"));

输出:

I appreciate you helping m out!

答案 2 :(得分:0)

请尝试以下代码段。理想情况下,它应该以通用方式工作。

    StringBuilder line = new StringBuilder(
            "I appreciate you helping me out!");

    System.out.println("Given input String :" + line);
    int lastOccuranceIndex = 0;
    int deleteIndex = 0;
    char[] charr = line.toString().toLowerCase().toCharArray();
    Map<Character, List<Integer>> charMap = new LinkedHashMap<Character, List<Integer>>();
    List<Integer> indexList = null;
    for (int i = 0; i < charr.length; i++) {
        if (charMap.containsKey(charr[i])) {
            indexList = charMap.get(charr[i]);
            indexList.add(i);
            charMap.put(charr[i], indexList);
        } else if (Character.isAlphabetic(charr[i])) {
            indexList = new ArrayList<Integer>();
            indexList.add(i);
            charMap.put(charr[i], indexList);
        }
    }
    for (Entry<Character, List<Integer>> entry : charMap.entrySet()) {
        indexList = entry.getValue();
        if (indexList.size() > 2) {
            // System.out.println(entry.getKey()
            // +" last but one : "+indexList.get(indexList.size() -2));
            if (indexList.get(indexList.size() - 2) > lastOccuranceIndex) {
                lastOccuranceIndex = indexList.get(indexList.size() - 2);
                deleteIndex = indexList.get(indexList.size() - 1);
            }
        }

    }
    System.out.println("last occurance character index  "
            + lastOccuranceIndex + " and the character to delete is :"
            + charr[lastOccuranceIndex]);
    char deleteChar = line.charAt(deleteIndex);
    System.out.println("deleteChar :" + deleteChar + " at index :"
            + deleteIndex);
    line = line.deleteCharAt(deleteIndex);
    System.out.println("String content after delete operation : " + line);

输出:

给定输入字符串:感谢您帮助我!

最后出现的字符索引18和要删除的字符是:e

deleteChar:e at index:26

删除操作后的字符串内容:感谢您帮助我!

答案 3 :(得分:0)

正规救援:

line = line.replaceAll("e(?=[^e]*$)", "");

正则表达式(?=[^e]*$)向前看要求e匹配后不会出现e