简体   繁体   中英

find character array length in Android

to get length of string

String str=strLenData.toString();
int ipLen= str.length();
return ipLen;

whatever be the value of strLenData , value of str = [C@40523f80 . As a result, for every char[] I input, the length is shown as 11.

I have to use the length as a limit to a loop. Many a times the actual length of char [] would be less than 11. In those cases, the application crashes with the java.lang.ArrayIndexOutOfBoundsException .

Is there any other method to find the length of array. In C++ we might look for '\\x0' to mark the end of string. But I guess that is not valid case in Android.

可能是同一行中的其他代码(可能是strCharData[i+j] )超出范围

The problem might be because of this,

strCharData[i+j]

Consider the length of strCharData to be 5. Now if you can see, you have used "i+j". Consider the result of i+j to be greater than 5. This will lead to a situation where you are referring to an index which is greater than the length of strCharData(say 5).

Or even this replaceLen value might be bigger than the total array size. Check it out

Java throws an out of bounds exception when you access an array outside its limits. In Java an array goes from 0 to length - 1.

In your case I would guess it is because replaceLen is too big, but could you please post the entire method so we can see?

Why are you using char arrays to do replacement? It's likely that you're better off using String.replaceAll, which accepts a regex. The regex can handle the 'match' part of your code and the replacement string doesn't have to be the same length as long as it matches the regex.

As Andro mentioned, the problem is almost definitely due to the i+j exceeding the bounds of the array and you're better off not using arrays at all.

String str=strLenData.toString();
int ipLen= str.length();

I assume strLenData is a char[]:

This code calls toString() on a char[], which returns garbage (I think it's something like a 2 char indicator of the data type + the hashcode of the array but that's not important). You then take the length of that String which is 11.

if strLenData is a char[] then you get the length with strLenData.length. It's a field not a method so there is no ().

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