简体   繁体   English

访问超出整数范围的字符串字符

[英]Accessing characters of a String beyond the range of Integer

I have a String/character sequence that is being repeated infinitesimally... Naturally ,characters will go out of range of Integer and start falling into range of Long, since methods used for accessing characters for both String as well as StringBuilder class all require an int "index" how do I access these characters at say , Long long>Intger.MAX_VALUE . 我有一个String/character序列,该序列将无限次重复...当然,由于用于访问String以及StringBuilder类的字符的方法都需要一个整数,因此字符将超出Integer的范围并开始落入Long的范围。 int "index"我如何访问这些字符,例如Long long>Intger.MAX_VALUE is there a way to override these methods such as charAt(int index) so that they start "accepting " long arguments ,if not so , how can I access the characters at this index, considered conversion to character array using String.toCharArray() method but then again, array length can only be upto Integer.MAX_VALUE . 有没有一种方法可以覆盖这些方法,例如charAt(int index)以便它们开始“接受”长参数,否则,如何访问此索引处的字符(考虑使用String.toCharArray()转换为字符数组String.toCharArray()方法,但同样,数组长度只能达到Integer.MAX_VALUE Is there a method/constructor type that I'm not aware of which accepts long arguments? 是否存在我不知道哪种method/constructor类型接受长参数的情况?

You should definitely not construct a string and do measurements on it. 您绝对不应构造字符串并对其进行测量。

This is a test on how well you are able to abstract things. 这是对抽象能力的测试。 I will give you some code you may study. 我会给你一些你可以学习的代码。 You should not copy+paste it for several reasons - including the possibility that I did some mistake. 您不应出于多种原因进行复制和粘贴,包括我犯了一些错误的可能性。

The idea is, to simply compute the information, which is possible because we have a simple repetition pattern. 这个想法是,仅计算信息,这是可能的,因为我们有一个简单的重复模式。

class RepeatedString {
    private String s;
    public RepeatedString(String s) {this.s = s;}

    public char charAt(long i) {
      return s.charAt((int)(i % s.length()));
    }

    public long count(char c, long i) {
      long n = 0;
      // how many complete repetitions?
      {
        long r = i / s.length();
        if (r > 0) {
          // count c in s
          for (int j = 0 ; j < s.length() ; j++) n += s.charAt(j) == c ? 1 : 0;
          n *= r;
        }
      }
      // how many c in last repitition
      {
        long l = i % s.length();
        for (int j = 0 ; j < l ; j++) n += s.charAt(j) == c ? 1 : 0;
      }
      return n;
    }
}

class Kata {

  public static void main(String[] args) {
    RepeatedString s = new RepeatedString("bla");

    System.out.println(s.charAt(1)); // expected 'l'
    System.out.println(s.charAt(6)); // expected 'b'

    System.out.println(s.count('a', 19)); // expected 6
    System.out.println(s.count('a', 21)); // expected 7
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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