1

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.

Liondancer
  • 15,721
  • 51
  • 149
  • 255
  • 1
    You can access the backing char array using reflection. – Thomas Jungblut Mar 11 '14 at 16:35
  • @ThomasJungblut not quite sure what this means sorry. could you further explain or provide an example – Liondancer Mar 11 '14 at 16:36
  • 2
    There's no sensible way. Unless they meant without using `String` at all - i.e. `int indexOf(char[] str, char[] find)` or similar. (Which is still not 'sensible', or course.) – Paul Mar 11 '14 at 16:37
  • Are you meant to implement that method for an instance of `String` or would the input already be `char[]`? If you get a `String` instance, are you sure you're not allowed to use `toCharArray()`? If that would be the case you're probably also not allowed to call other methods on `String` and thus you'd have to fall back to reflection, which is unsafe since you'd have to dive into the internals of `String`. This would be a really odd question for an interview as Java developer. – Thomas Mar 11 '14 at 16:39
  • @Paul that was what I thought as well. But I wasnt sure of what inputs I was given – Liondancer Mar 11 '14 at 16:39
  • Can you use the methods of the interface String implements? (CharSequence) – Gábor Bakos Mar 11 '14 at 16:40
  • @Thomas I guess I can try the question with `char[]` as input instead of string – Liondancer Mar 11 '14 at 16:40
  • 1
    At a minimum, you would have to have access to the `charAt()` method. – Bob Dalgleish Mar 11 '14 at 16:41
  • 2
    `String` implements `CharSequence`. So you could write the method entirely against the abstraction `CharSequence`. Would that count as not 'using' methods from `String`? – Paul Mar 11 '14 at 16:44
  • 1
    Could have been worse. They could have asked you to take a psychometric test. ;-) – Paul Mar 11 '14 at 16:47

5 Answers5

3

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • This helped a lot. I believe that this is the best answer and the interviewer would most likely have the method input as `char[]` – Liondancer Mar 11 '14 at 16:56
2

If your input is a CharSequence, you can do so like this:

CharSequence str = yourString;
char[] chars = new char[str.length()];
for (int i = chars.length; i-->0;) {
     chars[i] = str.charAt(i);
}
//chars now contains the characters of the string
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
1

That's a hard one; honestly I don't know.

I wonder of these answers help

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

There's one answer which uses StringCharacterIterator.

Community
  • 1
  • 1
Kevin Lee
  • 2,307
  • 26
  • 31
1
public static int customIndexOf(String string,char character) {
        String c = String.valueOf(character);
        Scanner sc = new Scanner(string).useDelimiter(Pattern.compile(""));
        int i=0;

        while(sc.hasNext()) {
            if (sc.next().equals(c)) {
                return i;
            }
            i++;

        }
        return -1;
    }
rpax
  • 4,468
  • 7
  • 33
  • 57
0

You can define an utility method that gets access to the value instance variable of String and returns the first position of a charachter in that string if it exists or -1 if it does not:

public class ReflectedUtils {

  public static final int indexOf(String s, char c)
  {
    int position = -1;
    try {
        Class clazz = Class.forName("java.lang.String");
        Constructor constructor = clazz.getDeclaredConstructor(clazz);
        String ztring = (String) constructor.newInstance(s);
        Field field = ztring.getClass().getDeclaredField("value");
        field.setAccessible(true);
        char[] chars = (char[]) field.get(ztring);
        for (int i=0; i<chars.length; i++)
        {
            if(chars[i] == c)
            {
                position = i;
                break;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    finally {
        return position;
    }
  }
  public static void main(String... args)
  {
    System.out.print(String.valueOf(ReflectedUtils.indexOf("Hello", 'e')));
  }
}
tmarwen
  • 15,750
  • 5
  • 43
  • 62