开发者

How can I get a string's length in Java without String API methods? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

String length without using length() method in java

I need to get the length of a string (no of characters present) in Java using a for loop and without using any methods like length().

import java.io.*;
import java.util.*;

public class reversestring

{
    public static void main(String arg[])throws IOException

    {
     String s;
     int i=0,j=0,k=0;
     DataInputStream in=new DataInputStream(System.in);
     System.out.println("Enter ur string : ");
     s=in.readLine();
     char ar[]=s.toCha开发者_如何学运维rArray();
     System.out.println("Length of the string is : ");

     for(j=ar[i];j!='\0';i++)
     {

         k++;

     }
     System.out.println(+k);
    }
}

I wrote this program, but I am not getting the answer. What is wrong with it?


This has been asked before. Here's my favorite answer:

str.lastIndexOf("")

(which probably even runs in constant time, as opposed to the other answers.)


The following .length is not a method.

int length = s.toCharArray().length


Java isn't C, thus you can't treat Java strings as C strings and you can't expect C methods to work in Java. In particular, Java strings aren't null-terminated.

The 'correct' way would be to use length (either a string method, or an array property), but, since you don't want, you could employ 'for each' loop.

for (char c in charArray) {
    ++count;
}

It feels not good, though.


a functional guy would answer

len(str)
   return str.isEmpty() ? 0 : 1+len(str.substring(1));


int counter;
String s = "something";

try{
    for(counter=0; s.charAt(counter); counter++);       

}catch(Exception e){
   //ArrayIndexOutOfBoundsException
   System.out.println("Length: " + counter);
}


I believe Java's String.toCharArray() returns an array that is not null-terminated, so looking for a null character would not work.


I can't believe all the other answers are using the String API, although the title of this question indicates that's not allowed :-P

I came up with this:

System.out.println(new StringReader("stackoverflow").skip(Long.MAX_VALUE));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜