Im working on a code where the user is asked to enter two strings as input. The first string can be multiple words. The second would have to have a lenght of one. If the lenght is not one it would give the user feedback. If the string is of length 1 it would then have top use a while loop to check each position in the first string and return the number of times the character occurs. So if user enter apple and then a, it would say there is 1 occurence. I havve to use a while loop and just keep it simple. I though the code was correct but it doesnt return any occurences. I know the if statement validates the second string is a character long. Am i using the other stamentes wrong?
It looks like you may want to substring your first input string and check if it is equal to the single character second entry.
Right now you are saying while a == apple, thats false so it just exits and wont print anything
posted 1 year ago
How would I substring the first string since this string can be any length.
posted 1 year ago
I misread your post.
You should be walking through the string in the while loop and checking that its equal to the character. No need to substring anything since you are already checking that they only gave you a char.
Just split the string into a list of chars, walk the list in the loop and compare it to the single second input char. Sound like you also should keep a count of how many times you find the char in the string and return or print that number.
Why is that a catch? My preference is to use Streams, then extended for, and only use an index if I need to know that. But even then, I would most likely use an IntStream for that. It's just what you got used to, I guess.
If you're going for readability, then yes, that is a good order. But when you look at performance, especially memory footprint, then the old loop is better for ArrayLists, and streams are probably the worst (unfounded, but I'm just guessing that it involves more objects than just an Iterator).
For Strings with toCharArray performance is actually going to be terrible for large Strings, because it first needs to create the char. Here are the Java 8 and 12 versions:
I'm not going into the StringLatin1 or StringUTF16 code, but essentially, in both versions the entire contents of the String is copied, and that takes both memory and CPU cycles. You actually loop over the String twice - once for creating the char and then once over the char.
Summarising: streams and for-each loops are great unless you really have to look at memory, and String.toCharArray() is the worst way to loop over a String.