Remove specific index from array in java

前端 未结 6 1327
情歌与酒
情歌与酒 2020-12-11 23:35

Can I remove a specific element from array by mentioning index value? For example can I remove the character d by giving index value 1?

<         


        
6条回答
  •  长情又很酷
    2020-12-12 00:20

    Using String class:

    char[] words = { 'c', 'd', 'f', 'h', 'j' };
    String str = new String(words);
    words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();
    

    Running in jshell:

    jshell> char[] words = { 'c', 'd', 'f', 'h', 'j' };
    words ==> char[5] { 'c', 'd', 'f', 'h', 'j' }
    
    jshell> String str = new String(words);
    str ==> "cdfhj"
    
    jshell> words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();
    words ==> char[4] { 'c', 'f', 'h', 'j' }
    
    jshell>
    

提交回复
热议问题