I am trying to implement a program in Java which reads and writes to text files and does various string manipulations.
I am struggling with this part of the program and hoping someone could help me figure this out:
Given input string, I need to keep all occurrences of lower and upper case letters that match what's in the file, delete all letters that do not match, and keep numbers and special characters in their place in the file.
For example, if a file contains this text "abc123ABC$$" and the user asks to keep "ab", then the result should be "ab123AB$$" (i.e. both lower and upper "a" and "b" kept in their place, and digits and special characters are not affected).
Right now, when keep = "ab", the function returns only "ab". Here is the code snippet:
public static String keepChar(String file, String keep) {
String result = "";
while(file.length() != 0)
{
int index = file.indexOf(keep);
if(index != -1)
{
result = result + file.substring(0,index) + keep;
file = file.substring(index + keep.length());
}
else
{
//result = result + file;
break;
}
}
return result;
}
What should I do? Any help would be very much appreciated.