kammaii / baguni

Second Korean app project
0 stars 0 forks source link

Can I make this code more simple? #5

Open kammaii opened 4 years ago

kammaii commented 4 years ago

I made searching flashcards feature. For example, if I want to find the word 'Student', I want to make it could be found without care of upper or lower case. I code below and it works whatever I put 'student', 'STUDENT', 'Student' in. (I couldn't make 'STdent' though.) But my code seems not clean because I used a lot of '||'. I know the method 'equalsEgnoreCase' but it's not real time. Because it should find every words contain 's' as soon as I put 's' in. My question is...

  1. Is it OK even though it seems not clean? or is there any simple way to make it?
  2. How can I code if I want to search with 'STdent' ?
            for(int i=0; i<listAllData.size(); i++) {
                String front = listAllData.get(i).getCollectionFront();
                String back = listAllData.get(i).getCollectionBack();
                if(front.toLowerCase().contains(text) || front.toUpperCase().contains(text) || front.contains(text) || back.toLowerCase().contains(text) || back.toUpperCase().contains(text) || back.contains(text)) { 
                    list.add(listAllData.get(i));
                }
            }
upgradingdave commented 4 years ago
@Test
  public void simpleRegex() {

    List<String> words = new ArrayList<String>();
    words.add("Student");
    words.add("Teachers");
    words.add("Study");
    words.add("school");

    for(String word : words) {

      Pattern pattern = Pattern.compile("^st", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(word);
      while (matcher.find()) {
        String matchedLetters = matcher.group();

        System.out.println("Word: " + word + ", Matched Letters: " + matchedLetters);
      }
    }
  }
upgradingdave commented 4 years ago

Hi Danny, this actually might be better. Use if instead of while. If you use while, you might get multiple results for the same vocabulary word.

@Test
public void simpleRegex() {

  List<String> words = new ArrayList<String>();
  words.add("Student");
  words.add("Teachers");
  words.add("Study");
  words.add("school");

  for(String word : words) {

    Pattern pattern = Pattern.compile("^st", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(word);
    **if(matcher.find()) {**
      String matchedLetters = matcher.group();
      System.out.println("Word: " + word + ", Matched Letters: " + matchedLetters);
    }
  }
}