简体   繁体   中英

how can I make charAt method work with arrays in java?

can someone help me with this problem? i have to make method charAt to work but i dont know how..

class AsciiCharSequence implements java.lang.CharSequence/* extends/implements */ {
    // implementation
    byte[] array;

    public AsciiCharSequence(byte[] array) {
        this.array = array.clone();
    }

    @Override
    public int length() {
        return array.length;
    }

    *@Override
    public char charAt(int i) {
        return (char) array.length(i);
    }*

Try this:

@Override
public char charAt(int i) {
    return (char) array[i];
}

Since you have an array and want to return the character at a particular array. In your question you are not returning a particular index value.

Use [] to access element in the array. But do not forget about throwing required exception, like it declared in CharSequence documentation (if you access not correct element in an array, another type of exception will be thorwn).

public class AsciiCharSequence implements CharSequence {

    private static final char[] EMPTY_ARRAY = new char[0];

    private final char[] arr;

    public AsciiCharSequence(char[] arr) {
        this.arr = arr == null || arr.length == 0 ? EMPTY_ARRAY : Arrays.copyOf(arr, arr.length);
    }

    private AsciiCharSequence(char[] arr, int start, int end) {
        this.arr = arr == null || arr.length == 0 || start == end ? EMPTY_ARRAY : Arrays.copyOfRange(arr, start, end);
    }

    @Override
    public int length() {
        return arr.length;
    }

    @Override
    public char charAt(int i) {
        if (i < 0 || i >= length())
            throw new IndexOutOfBoundsException();

        return arr[i];
    }

    @Override
    public AsciiCharSequence subSequence(int start, int end) {
        if (start < 0 || end < 0)
            throw new IndexOutOfBoundsException();
        if (end > length())
            throw new IndexOutOfBoundsException();
        if (start > end)
            throw new IndexOutOfBoundsException();

        return new AsciiCharSequence(arr, start, end);
    }

    @Override
    public String toString() {
        return IntStream.range(0, arr.length).mapToObj(i -> String.valueOf(arr[i])).collect(Collectors.joining());
    }
}

For better understanding about character set can be refer below code from 的代码

 @Override
public char charAt(int index) {
    checkIndex(index, count);
    if (isLatin1()) {
        return (char)(value[index] & 0xff);
    }
    return StringUTF16.charAt(value, index);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM