How to replace a whole string with another in an array in Java

后端 未结 2 1040
天涯浪人
天涯浪人 2021-01-27 16:45

I want to replace, say String oldString with String newString in an Array along the lines of:

f         


        
2条回答
  •  半阙折子戏
    2021-01-27 17:32

    You can use IntStream over the indices of this array and process certain strings in a certain way:

    String[] text = {"Lorem", "oldString", "dolor", "sit", "amet"};
    
    IntStream.range(0, text.length)
            // to filter the certain strings, or you
            // can skip this line to process each string
            .filter(i -> text[i].equals("oldString"))
            // processing a string
            .forEach(i -> text[i] = text[i].replace("oldString", "newString"));
    
    System.out.println(Arrays.toString(text));
    // [Lorem, newString, dolor, sit, amet]
    

    See also: Replace certain string in array of strings

提交回复
热议问题