0

I need to iterate through the String userInput and find if the char is a letter or digit, if it is then I need to append that char to the String endProduct.

    public static String converter(String userInput) {
        String endProduct = "";
        char c = userInput.charAt(0);
        Stack<Character> stack = new Stack<Character>();
        int len = userInput.length();
        //iterates through the word to find symbols and letters, if letter or digit it appends to endProduct, if symbol it pushes onto stack
        for (int i = c; i < len; i++) {
            if (Character.isLetter(userInput.charAt(i))) {
                endProduct = endProduct + c;
                System.out.println(c);
            }//end if
            else if(Character.isDigit(userInput.charAt(i))){
                endProduct = endProduct + c;
                System.out.println(c);
            }
Natedog
  • 13
  • 2
  • What is the ask here? Can confirm that the userInput starts with the index where the iteration should start? You might mean "for (int i = 0..." – Jayr Nov 25 '19 at 20:00

1 Answers1

2

Here are some ways to accomplish this.

Method 1 - traditional Java.

private static String converter(String userInput) {
  final StringBuilder endProduct = new StringBuilder();

  for(char ch : userInput.toCharArray()) {
    if(Character.isLetterOrDigit(ch)) endProduct.append(ch);
  }

  return endProduct.toString();
}

Method 2 - Streams.

private static String converter(String userInput) {
  int[] chars = userInput.codePoints().filter(Character::isLetterOrDigit).toArray();

  return new String(chars, 0, chars.length);*/
}

or

private static String converter(String userInput) {
  return userInput.codePoints().filter(Character::isLetterOrDigit).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
Oliver
  • 405
  • 6
  • 15