Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to find the number of characters in a string

 
s john smith
Greenhorn
Posts: 16
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to find the number of characters in a string without using standard library functions?
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseOneThreadPerQuestion.(⇐click)
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd say so.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic