Created
March 2, 2017 12:00
-
-
Save gokhanaliccii/0c999645e68c15802234cf158e22a339 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.ArrayList; | |
/** | |
* Created by gokhan on 02/03/17. | |
*/ | |
public class CharacterRemover { | |
public String removeExtraCharacters(String input, int limit) { | |
if (input == null) | |
return null; | |
//throw exception | |
if (limit < 0) | |
return input; | |
//find distinct characters | |
ArrayList<Character> mDistinctChars = findDistinctChars(input); | |
//throw exception | |
if (mDistinctChars == null) | |
return input; | |
//iterate characters and remove if need | |
for (Character character : mDistinctChars) { | |
//ignore white space | |
if (Character.isWhitespace(character)) | |
continue; | |
int count = findCharacterCount(character, input); | |
if (findCharacterCount(character, input) < limit) | |
continue; | |
input = removeCharacters(input, character); | |
} | |
return input; | |
} | |
/** | |
* @param word | |
* @return distinct characters | |
*/ | |
private ArrayList<Character> findDistinctChars(String word) { | |
ArrayList<Character> mDistinctChars = new ArrayList<>(); | |
char characters[] = word.toCharArray(); | |
for (Character c : characters) { | |
if (!mDistinctChars.contains(c)) | |
mDistinctChars.add(c); | |
} | |
return mDistinctChars; | |
} | |
/*** | |
* @param word | |
* @param c | |
* @return remove wanted character | |
*/ | |
private String removeCharacters(String word, char c) { | |
return word.replaceAll(String.valueOf(c), ""); | |
} | |
/** | |
* @param word | |
* @param c | |
* @return remove wanted word | |
*/ | |
private String removeCharacters(String word, String c) { | |
return word.replaceAll(c, ""); | |
} | |
/** | |
* @param c search character | |
* @param word | |
* @return count of character | |
*/ | |
private int findCharacterCount(char c, String word) { | |
if (word == null || word.length() == 0) | |
return 0; | |
char wordChars[] = word.toCharArray(); | |
int counter = 0; | |
for (int index = 0; index < wordChars.length; index++) { | |
if (wordChars[index] == c) | |
counter++; | |
} | |
return counter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment