-
Notifications
You must be signed in to change notification settings - Fork 0
01. Remove Specific String From String Array
prabhatrocks07 edited this page Jun 14, 2019
·
5 revisions
public class RemoveStringFromArray {
public static void main(String[] args) {
String[] strArray = {"Hi", "Hello", "Hey", "Here", "Happy", "hmmm"};
System.out.println("Original Array : \n" + Arrays.toString(strArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string to be removed : ");
String input = sc.next();
sc.close();
strArray = removeStringFromArray(strArray, input);
System.out.println("Array after modification : \n" + Arrays.toString(strArray));
}
private static String[] removeStringFromArray(String[] strArray, String input) {
if(strArray == null) {
return null;
} else if(strArray.length <= 0) {
return strArray;
} else {
/* Using Array with fixed length */
//String[] newArray = new String[strArray.length - 1];
//int j = 0;
/* Using list to avoid ArrayIndexOutOfBoundException when no matching input */
List<String> list = new ArrayList<>();
for (int i = 0; i < strArray.length; i++) {
if(!input.equals(strArray[i])){
//newArray[j] = strArray[i];
//j++;
list.add(strArray[i]);
}
}
// return newArray ;
return list.toArray(new String[list.size()]);
}
}
}