How can I remove all non-numeric elements from an array? - java

I have a String array which contains both integer and non-integer elements, and I need to remove all the non-integer elements of that array.
Now I am only able to remove the non-integer content in a single string, but I need to remove the entire non-integer elements in an array.
My snippet as follows
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Can anyone help me to achieve it?

You can achieve it by below code
Pattern p = Pattern.compile("\\d*");
String [] array=new String[]{"23","33.23","4d","ff"};
List<String> lst=new ArrayList<String>();
for (int i=0; i<array.length; i++) {
if(p.matcher(array[i]).matches()){
lst.add(array[i]);
}
}
System.out.println(""+lst);

Your original code is this:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
First, if you need to remove all non-integer character, you need to change your regex from "[^\d.]" to "[^\d]".
Yours will not remove dots character.
Then, you said:
Now I am only able to remove the non-integer content in a single
string, but I need to remove the entire non-integer elements in an
array.
Maybe I'm not getting this right, but isn't just a matter of looping while doing the same thing ? You didn't show us any code with loops, but perhaps your true problem is reassigning the modified value to the array ?
try this:
for(int i=0;i<strArray.length;i++){
strArray[i] = strArray[i].replaceAll("[^\\d]", "");
}
MAYBE you were doing something like this ? (this does not work):
for(String str: strArray){
str = str.replaceAll("[^\\d]", "");
}
That doesn't work because the modified string is not reassigned to the array, it is assigned to the new variable 'str'. So this code does not update the value pointed by the array.

replace all numbers - str = str.replaceAll("\\d", "");
replace all non-numbers - str = str.replaceAll("[^\\d]", "");
to do so in an array, iterate over the Array and do the replacment.

To remove all the non-integer values form a string you can try the following:
public boolean isInt(String s)
{
for(int i = 0; i < s.length(); i++)
{
try
{
Integer.parseInt(String.valueOf(s.charAt(i)));
}catch(NumberFormatException e)
{
return false;
}
}
return true;
}
Then you can iterate your array and remove the non-integer elements like this
for(int i = 0; i < arr.length; i++)
{
if(isInt(arr[i]))//remove the element
}

It would probably be easier to remove elements from a list than from an array. However, you can stream the elements of the array, remove invalid elements with flatMap, and then convert back to an array.
When using flatMap, each element in the input can produce zero, one, or many elements in the output, so we map the valid ones to singleton streams containing just that element, and the invalid ones to empty streams, thus removing them from the result.
String[] result = Arrays.stream(input)
.flatMap(a -> Pattern.matches("\\d+", a)?
Stream.of(a) : Stream.empty())
.toArray(String[]::new);

If your regex is working correctly, you already solved most of your problem. You only need to use your code in a for loop. You can try the code below:
public String[] removeNonIntegersFromArray(String[] array){
ArrayList<String> temp = new ArrayList<String>();
for (int i=0; i<array.length; i++) {
String str = array[i];
if(!str.matches(".*[^\\d]+.*")){
temp.add(str);
}
}
String[] result = new String[temp.size()];
result = (String[]) temp.toArray(new String[temp.size()]);
return result;
}
Edit: I refactored the code as it will delete whole array element which has non-integer.

Here is an idea,
Instead of replacing all non-int number, to find all integer and add them to a new string.
for(int i=0;i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
new_str.append(str.charAt(i));
}

Related

Comparing array items, index out of bound

I have a piece of code and I'm a bit confused how to deal with my issue so, please review method below. I was trying to search for a solution but unfortunately none of them fit my needs so I am looking for an advice here. The method is taking a String and removing duplicated characters so for example - input: ABBCDEF should return ABCDEF, but when entering i+1 in the last iteration I got IndexOutOfBound Exception, so I can iterate until string.length-1 but then I loose the last element, what is the SMARTEST solution in your opinion, thanks.
public String removeDuplicates(String source){
if(source.length() < 2){
return source;
}
StringBuilder noDuplicates = new StringBuilder();
char[] string = source.toCharArray();
for(int i = 0; i < string.length-1; i++){
if(string[i] != string[i+1]){
noDuplicates.append(string[i]);
}
}
return noDuplicates.toString();
}
You could do this like so: append the first character in source, and then only append subsequent characters if they are not equal to the previously-appended character.
if (source.isEmpty()) {
return source; // Or "", it doesn't really matter.
}
StringBuilder sb = new StringBuilder();
sb.append(source.charAt(0));
for (int i = 1; i < source.length(); ++i) {
char c = source.charAt(i);
if (c != sb.charAt(sb.length() - 1)) {
sb.append(c);
}
}
return sb.toString();
But if you wanted to do this more concisely, you could do it with regex:
return source.replaceAll("(.)\\1+", "$1");
You could simply append the last character after the loop:
public String removeDuplicates(String source){
...
noDuplicates.append(string[string.length - 1]);
return noDuplicates.toString();
}
You have a simple logic error:
You make your string to a char array.
That is fine, but the length property of any array will show you the
human way of counting if someting is in it.
If there is 1 element the length will be 1
2 -> 2
3 -> 3
etc.
You get the idea.
So when you go string[i + 1] you go one character to far.
You could just change the abort condition to
i < = string.length - 2
Or you could write a string iterator, to be able to access the next element, but
that seems like overkill for this example
This is just what LinkedHashSet was made for! Under the hood it's a HashSet with an iterator to keep track of insertion order, so you can remove duplicates by adding to the set, then reconstruct the string with guaranteed ordering.
public static String removeDuplicates(String source) {
Set<String> dupeSet = new LinkedHashSet<>();
for (Character v : source.toCharArray()) {
dupeSet.add(v.toString());
}
return String.join("", dupeSet);
}
If you wish to remove all repeating characters regardless of their position in the given String you might want to consider using the chars() method which provides a IntStream of the chars and that has the distinct() method to filter out repeating values. You can then put them back together with a StringBuilder like so:
public class RemoveDuplicatesTest {
public static void main(String[] args) {
String value = "ABBCDEFE";
System.out.println("No Duplicates: " + removeDuplicates(value));
}
public static String removeDuplicates(String value) {
StringBuilder result = new StringBuilder();
value.chars().distinct().forEach(c -> result.append((char) c));
return result.toString();
}
}

Java: Removing an empty Element from String Array [duplicate]

This question already has answers here:
Resize an Array while keeping current elements in Java?
(12 answers)
Closed 3 years ago.
I have an array String ar[] = {"HalloWelt", " "};, ar.length is 2.
It does register two values within "HalloWelt" on index 0, and a blank/empty string on index 1;
I wonder how can I remove empty space on the index 1 - > but also keep it as a String Array since it is necessary for next task. Or how to do bunch of conversions but end up with String Array in the end.
My attempt
public String[] arraysWhiteSpaceEliminator(String[] arr) {
int k=0; //Identify how big the array should be i.e. till it reaches an empty index.
for(int i=0; i<bsp.length;i++) {
arr[i].trim();
System.out.println(arr[i].isEmpty());
if(arr[i].isEmpty()) {
}
else {
k = k+1; //if the index isn't empty == +1;
}
}
String[] clearnArray = new String[k];
for(int s = 0; s<k; s++) {
clearnArray [s] = arr[s]; //define New Array till we reach the empty index.
//System.out.println(clearnArray [s]+" " +s);
}
return clearnArray ;
};
The logic is very simple:
Identify how big the clearnArray should be.
Iterate through original Array with .trim() to remove white Space and check wether isEmpty().
Add to the k if the index isnt Empty.
Create clearnArray with the k as size.
Loop through originial Array till k -> add all the items to cleanArray till k.
Issue: .trim() and .isEmpty() don't record that the index is empty. ?!
A solution with streams:
String[] clean = Arrays.stream(ar)
.map(String::trim)
.filter(Predicate.isEqual("").negate())
.toArray(String[]::new);
Note that this assumes none of the array elements are null. If this is a possibility, simply add the following stage before the map:
.filter(Objects::nonNull)
The problem with your code is that after counting to find k, you just write the first k elements from the original array. To solve the problem by your technique, you need to check each element of the input array again to see if it's empty (after trimming), and only write to the new array the elements which pass the test.
The code can be simplified using the "enhanced" for loop, since you don't need indices for the original array. (The variable i keeps track of the current index in the new array.) Note also that strings are immutable, so calling .trim() does nothing if you don't use the result anywhere. Your code also refers to bsp which is not defined, so I changed that.
int k = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
k++;
}
}
String[] cleanArray = new String[k];
int i = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanArray[i] = s;
i++;
}
}
return cleanArray;
Calculate the number of non-null elements and create an array of that size, like
String[] strs = ...;
int count = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) count++;
}
String newStrArray[] = new String[count];
int idx = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) newStrArray[idx++] = strs[i];
}
return newStrArray;
You could also probably make this prettier using streams. However I haven't used streaming functionality in Java, so I can't help there.
Two things to note:
Unless you are serializing or the nulls are causing other problems, trimming the array just to get rid of the nulls probably won't have an impact on memory, as the size of an array entry (4 bytes) is very likely inconsequential to the memory block size allocated for the Array object
Converting first to an List and then back to an array is lazy and possibly inefficient. ArrayList, for example, will likely include extra space in the array it creates internally so that you can add more elements to the ArrayList and not have to create a whole new internal array.
in your method, create a new
List cleanedList = new ArrayList();
add iterate through ar[]ar[] = ["HalloWelt",""], and add only non-empty values to cleaned List....then return the array.
return cleanedList.toArray()
like below:
List<String> cleanedList = new ArrayList<>();
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanedList.add(s);
}
}
return cleanArray.toArray();

Getting Index of Arraylist in Java

ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
I want to compare a string to one of the elements of the array.
String b = "Test1";
b.equals(str[index??]);
How can i get the index of str?
It's an arrayList. Therefore, to store a value of the array with a certain index, use this:
ArrayList.get(index);
Now, you can make this equal to a variable like this:
String mStr = ArrayList.get(index);
If I have an arrayList with the values "1, 2, 3, 4" it's important to note, index 0 is the value 1.
ArrayList.get(0) //HERE, THE INDEX IS ZERO, MEANING THE VALUE OF THE ARRAY LIST WOULD BE 1
Output:
1
That is easily confused; index 0 = first value. Just be sure to use the get() method.
To further compare strings, set that values equal to strings:
String FIRSTSTRING= ArrayList.get(0);
String SECONDSTRING= ArrayList.get(1);
Here, I am comparing the first and second values of the array list.
If you found this helpful, mark it as best answer. If you need more help, feel free to ask me, I am always happy to help!
{Ruchir}
You want List.get(int) (where int is the index). For example,
List<String> al = Arrays.asList("Test1", "Test2");
System.out.println(al.get(0).equals("Test1"));
the output is
true
You can try something like this
ArrayList<String> str = new ArrayList<String>();
...
boolean found = false;
for(String string : str)
found =b.equals(string);
Other than that,you can use get method of list.
You can use indexOf() method.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
System.out.println(str.indexOf("Test1"));
If you want to use the str.get(index) method and then check use a loop, But I find this more complicated.
for(int i = 0; i < list.size(); ++i)
if(list.get(i).equals("rtes"))
return i;
Use Binary Search if your Array is sorted. Otherwise, just go linearly in the arraylist, and compare the values.
in your case:
boolean find = false;
for(i=0;i<str.length;i++){
if(str.get(i) == b){
find = true;
break;
}
}

Convert String elements to Array

I have a String :
str="[a],[b],[c]";
How can I convert str to array in Java (Android):
array[0] -> a
array[1] -> b
array[2] -> c
EDIT:
and what about multidimensinal array? str="[["a1","a2","a3"],["b1","b2","b3"]]";
try
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");
===========================================
update
converting multi dimension array to single dimension is already answered in SO please check change multidimensional array to single array
just copied the solution
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
You can use following way.
String Vstr = "[a],[b],[c]";
String[] array = Vstr.replaceAll("\\]|\\[", "").split(",");
You would need to process your string and build your array. You could either take a look at .split(String regex) (which might require you to do some more processing to clean the string) or else, use a regular expression and do as follows:
Use a regex like so: \[([^]]+?)\]. This will seek out characters in between square brackets and put them into a group.
Use the .find() method available from the Matcher class and iterate over the matches. Put everything into a list so that you can put in as many hits as you need.
If you really need the result to be in an array, use the .toArray() method.
Take a look at String.split() method
An alternative to the regex and what npinti, i think, is talking about:
String myStrg = "[a],[b],[c]";
int numCommas = 0;
for( int i = 0; i < myStrg.length(); i++ )
{
// Count commas
if( myStrg.charAt(i) == ',' )
{
numCommas++;
}
}
// Initialize array
myArry = new String[numCommas];
myArry = myStrg.split(",");
// Loop through and print contents of array
for( String arryStrg: myArry )
{
System.out.println( arryStrg );
}
Try this code.
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Categories