I need to shorten a char[]. I just want to get rid of the first letter
I need to shorten my char[] by one letter each time I pass through the code. The arguments I'm using are hello and hel. It should return true false fals开发者_运维技巧e. At least that's what I think it should return. I think what I have so far is close:
private void doDountSubStringMatchRecursive(String target, String key){
char[] targetChar= target.toCharArray();//long one
char[] keyChar= key.toCharArray();//short one
for (int i = 0; i <=targetChar.length- keyChar.length; i++ ){
System.out.println(testHelper(targetChar , keyChar));
String recursive = targetChar.toString(); //Turns into a string
targetChar = recursive.substring(1).toCharArray();//moves my string starting point over by one and converts the char[]
System.out.println(targetChar.toString() + " " + keyChar.toString() );
}
}
private boolean testHelper(char[] targetChar , char[] keyChar){
boolean test = false;
for (int i=0; i <= keyChar.length - 1; i++){ // runs through the char[] and states the test
if (keyChar[i] == targetChar[i]) {
test = true;
} else {
return false;
}
}
return test;
}
And this is my output:
true
[C@24c21495 [C@41d5550d
false
[C@1cc2ea3f [C@41d5550d
false
[C@40a0dcd9 [C@41d5550d
false
[C@1034bb5 [C@41d5550d
false
[C@7f5f5897 [C@41d5550d
false
[C@4cb162d5 [C@41d5550d
false
[C@11cfb549 [C@41d5550d
false
[C@5b86d4c1 [C@41d5550d
false
[C@70f9f9d8 [C@41d5550d
I don't get what this is doing now. And yes I know I could just find occurrence of the key by using indexof(key).
It's not clear exactly what your code is supposed to do, as you haven't really stated the problem very clearly. However, there is one bug that you should fix right away:
targetChar.toString()
does not do what you think it does. It gives you the String representation of the char array object (which is something like "C@24c21495"), not an interpretation of that array as a sequence of characters. If you want a String
representing the sequence of characters in the array, then you want to call
String.valueOf(targetChar)
or
new String(targetChar)
to convert the char[]
into a more helpful String
.
This change might help you debug the rest of your code.
Firstly, in java, array.toString()
is useless; you must use Arrays.toString(array)
. Change your code to this:
System.out.println(Arrays.toString(targetChar) + " " + Arrays.toString(keyChar) );
FYI, Josh Bloch considers this a big mistake in java. I agree.
精彩评论