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.

10
  • 1
    You can access the backing char array using reflection. Commented Mar 11, 2014 at 16:35
  • 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.) Commented Mar 11, 2014 at 16:37
  • 1
    At a minimum, you would have to have access to the charAt() method. Commented Mar 11, 2014 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? Commented Mar 11, 2014 at 16:44
  • 1
    Could have been worse. They could have asked you to take a psychometric test. ;-) Commented Mar 11, 2014 at 16:47

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This helped a lot. I believe that this is the best answer and the interviewer would most likely have the method input as char[]
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

2 Comments

You have used both length() and chatAt() methods, so I assume not the best answer!
@tmarwen Well, those are both CharSequence methods, not specific to Strings.
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.

Comments

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;
    }

Comments

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')));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.