有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重载的StringBuilder insert()以及偏移量和索引之间的差异

我只是想知道,在指示可以插入指定参数的位置时,偏移量和索引的语义是否有任何区别(可以是String、Object、char[]等类型)。例如,所有两个参数insert()重载方法都将该位置称为“offset”。然而,这一点:

public StringBuilder insert(int index, char[] str, int offset, int len)

使用“索引”来指代字符串中发生插入的位置。 从技术上讲,我认为正确的术语应该是“offset”,但我只是想知道,为什么类设计人员在基本上相同的操作中使用了两个不同的术语

谢谢


共 (1) 个答案

  1. # 1 楼答案

    javadoc

    Inserts the string representation of a subarray of the str array argument into this sequence. The subarray begins at the specified offset and extends len chars. The characters of the subarray are inserted into this sequence at the position indicated by index. The length of this sequence increases by len chars.

    所以:

    • offsetstr相关,即您要添加到StringBuilder内容中的char[]
    • indexStringBuilder中的实际内容相关

    特别是javadoc:

    index - position at which to insert subarray.

    str - A char array.

    offset - the index of the first char in subarray to be inserted.

    len - the number of chars in the subarray to be inserted.


    下面是一个示例代码:

        String originalContent = "1234567890";
        char[] charArray = new char[]{'a', 'b', 'c', 'd'};
    
        StringBuilder a = new StringBuilder(originalContent);
        a.insert(2, charArray, 0, 1);
        System.out.println(a.toString()); // Prints 12a34567890
    
        StringBuilder b = new StringBuilder(originalContent);
        b.insert(0, charArray, 2, 1);
        System.out.println(b.toString());   // Prints c1234567890