aspose file tools*
The moose likes Beginning Java and the fly likes how to find the number of characters in a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to find the number of characters in a string" Watch "how to find the number of characters in a string" New topic
Author

how to find the number of characters in a string

s john smith
Greenhorn

Joined: Jan 12, 2012
Posts: 16

how to find the number of characters in a string without using standard library functions?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

You don't. This is probably some interview question to make you think outside the box, but the answer is simple - it's not possible. The obvious choice, String.length(), is not allowed. Another approach is to get the length of the backing char[], but that requires a call to toCharArray() - not allowed. Yet another approach is to get the next character until you encounter an IndexOutOfBoundsException (which you catch), but guess what - getting the character requires charAt(index) which is also not allowed.

If you use our search you'll find a few more threads with the same question, and the answer is going to be the same.

I found one such thread, but that only disallowed using length(). You're not allowed to use anything.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

I was gonna say print it to the screen and count, but even that requires a System.out.println() call, which is - you guessed it - not allowed.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Please UseOneThreadPerQuestion.(⇐click)
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Sounds to me like a question about C that's been translated to Java without realising it doesn't make sense in Java. In C you've got pointer arithmetic and null-terminated strings, and this would be a reasonable question.
Rod Singh
Greenhorn

Joined: Feb 10, 2012
Posts: 16
In c language, you can write a function to calculate length of a string, and let your java program call it using JNI.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

Rod Singh wrote: In c language, you can write a function to calculate length of a string, and let your java program call it using JNI.

wouldn't using the JNI require you to use "standard library functions"?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

I'd say so.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to find the number of characters in a string