2

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.

Anna Diaz
  • 85
  • 6

2 Answers2

1

Check the below piece of code if it suits you :

Given a string "abc123ABC$$" and a user input "bc" , it prints "bc123BC$$"

String input = "bc";
String sample = "abc123ABC$$";
String result = "";    
for (int i = 0; i < sample.length(); i++) {
     if (input.toUpperCase().contains(String.valueOf(sample.charAt(i)).toUpperCase())
             || (!Character.isLetter(sample.charAt(i)))) {
         result+=String.valueOf(sample.charAt(i));
     }
}
System.out.println(result);

UPDATE :

As per your last comment, if you want to keep digits too based on the user input then the if statement should be as below :

if (input.toUpperCase().contains(String.valueOf(sample.charAt(i)).toUpperCase())
                    || ((!Character.isLetter(sample.charAt(i))) && (!Character.isDigit(sample.charAt(i)))) ) {
nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • If I wanted this function to keep the digits as well, how would I modify it? For example, if sample is "abc123ABC$$" and user input is "bc13", the result should be "bc13BC$$". I have been trying to modify this code and test it in many ways, but could not get the desired outcome. Any suggestions would be greatly appreciated. – Anna Diaz Nov 15 '19 at 02:32
0

If you don't find keep ('ab' in your example), you break. So with your example, on first iteration you get 'ab'. On second iteration, you have 'c123ABC$$' left, so you go in your else part and break.

For your use case, replaceAll with a regex seems a good fit. Looking at this question can help you : Is it possible to invert a call to String's replaceAll method?

Thomas Martin
  • 678
  • 8
  • 19