I am practicing for interviews and I am given a question to create the String method indexOf
without the use of string methods. My first thought was to process the String into a char[]
but I am not sure how to do so without the use of .toCharArray()
If anyone has ever had this interview question asked to them I would love your input.
Without using any method provided by String
the only option to "convert" a string to a character array would be the use of reflection:
char[] c = String.class.getDeclaredField( "value" ).get( "your string" );
Note that you'd have to catch exceptions etc.
And a big note: this is very unsafe, since you never know if the field is called value
in any implementation. This is not an intended usage of the String
class. Also note that the resulting array might be bigger than the actual string, i.e. the null termination character might be at any location.