I want to find the character at a particular position of a very large string. However i am unable to use charAt()
method because the range exceeds that of int. Is there a tweak to this?
Asked
Active
Viewed 6,800 times
10

user2133404
- 1,816
- 6
- 34
- 60
-
3Your string is over 2 billion characters long? – rgettman Jan 24 '14 at 21:47
-
yeah.. I want to find character at position '2298867968' – user2133404 Jan 24 '14 at 21:48
-
probably best to break it up into smaller strings to begin with – Paul Dardeau Jan 24 '14 at 21:49
-
1So, when you print out the length of the `String`, it's a negative number? – Josh M Jan 24 '14 at 21:52
-
The string generates itself based on that position value. For ex: if charAt(i)=='1' then the present character will be 2 etc. So I need to compare using charAt() function for larger values – user2133404 Jan 24 '14 at 21:52
-
See http://stackoverflow.com/questions/1179983/how-many-characters-can-a-java-string-have for max string length – Henry Jan 24 '14 at 21:52
-
Then isnt my string even being created ? – user2133404 Jan 24 '14 at 21:53
-
1If you're trying to create it, no it's probably not being created. Or not with the length you're expecting. Show how you're creating it, I guess. – Radiodef Jan 24 '14 at 22:10
3 Answers
15
In Java, Strings are backed by a character array. The theoretical size of an array is limited by the maximum value of int
, so it's impossible to have a String with over 231-1 characters to begin with.
To overcome this issue you can create a string class of your own that uses multiple arrays or strings as storage.

Joni
- 108,737
- 14
- 143
- 193
0
Would taking just a shorter substring from the large string and accessing the corresponding position help?

fedorSmirnov
- 701
- 3
- 9
- 19
-
Nope,its a dynamically generating string based on a pre determined position. the position itself is out of integer scope. – user2133404 Jan 24 '14 at 21:49
-
Well but if you know that position, you can cut off the first x characters and then access the position minus x – fedorSmirnov Jan 24 '14 at 21:51
0
As the String is internally represented by array of chars its maximal length cannot be bigger than size of int. So in the first place you cannot have String that exceeds range of int.

Matej
- 36
- 4