sara said:
Hi All,
Is there any way to know the end of a string not by using length()
function?
e.g. in C the last character is \0
Thanks.
Ditto what everyone else said. There are times, though, when your
"string" won't be a String, but rather an array of char (or even int) in
a buffer that you read from some low-level source. The Javanese way to
handle that situation is to keep separate integers denoting the index
and size of the valid buffer content at all times. If you really wanted
to do things the C way, you could try something like this:
import java.io.PrintWriter;
public class Main {
/**
* Probably useless, put plausible if you're using multiple string
* classes that do not all implement any common interface having a
* length() method.
*/
public static int strlen(String s) {
return s.length();
}
/** Horribly named function, since it doesn't take a String. */
public static int strlen(char[] buffer)
throws IllegalArgumentException {
for(int i = 0; i < buffer.length; ++i) {
if(buffer
== '\u0000') {
return i;
}
}
throw new IllegalArgumentException(
"unterminated C-style string");
}
private static void init(char[] buffer, String s) {
for(int i = 0; i < s.length() && i < buffer.length; ++i) {
buffer = s.charAt(i);
}
}
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out, true);
final int BUFSIZE = 1024;
char[] buffer = new char[BUFSIZE];
init(buffer, "hello");
out.println(strlen("A string."));
out.println(strlen(buffer));
}
}