get count of string with commas and split them - java

I am new to java . I have this String.
str="plane,cat,red,dogy";
I want to make a loop and send the data . the below is wrong but i want something similar to it.
for ( int i = 0; i>str.length; i++)
{
str=split.string(,);
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}

This should be what you are looking for:
String str="plane,cat,red,dogy";
for(String subString: str.split(",")){
updatestatement(subString);
}

String[] words= str.split(",");
for (String w : words){
//Do whatever you want with each word
}

Don't use for to split. Just:
String[] parts = str.split(",");

It is very unclear what you need. But i think you are looking for this:
String[] s = str.split(",");
for ( int i = 0; i<s.length; i++)
{
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}
Where updatestatement is a method in your class

The answer is simple.
String str="plane,cat,red,dogy";
String[] items = str.split(",");
System.out.println("No of items::"+items.length);
If you want to print each item,
for (String eachItem : items) {
System.out.println(eachItem);
//updateStatement(eachItem);
}

You should do it as follows :
String str="plane,cat,red,dogy";
String[]str1=str.split(",");
for ( int i = 0; i>str1.length; i++)
{
updatestatement(str1[i]);
}

String str="plane,cat,red,dogy";
String[] parts = str.split(",");
Arrays.stream(parts).forEach(System.out::println);
This solution only works with Java 8 because of the stream method. If you remove the last line it also works with other Java versions.

Related

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

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));
}

arrays splitting strings java

I'm sure this is a fairly easy question for someone but I cant work out the best way to do it as a relative beginner.
I am splitting a large file (the string temp) into about a 100 strings and setting it as an array, but I don't know the exact number of strings.
String[] idf = temp.split("===========");
String class1 = idf[0];
String class2 = idf[1];
String class3 = idf[1];
etc etc..
What is the best way to ensure that I can split all the strings and store them in an array?
Any suggestions or pointers would be most appreciated thanks!
You can do it like this:
String list = "hey there how are you";
String[] strarray = list.split("\\s+");
for (String str: strarray)
{
System.out.print(str);
}
Probably you want to iterate over your String array.
You can do it like that:
for(String s : idf) {
//operate on s here
}
Use for-each to get elements from array.
Please look at oracle official site for for-each loop.
Consider below code.
String tempString = "";
String regex = "";
String[] temparray = tempString.split(regex);
for (String temp : temparray)
{
System.out.println(temp);
}

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)

How to split Java String using REGEX into array

I have got a Java String as follows:
C|51199120|36937872|14261248|0.73|I|102398308|6240560|96157748|0.07|J|90598564|1920184|8867 8380|0.0
I want split this using regex as String arrays:
Array1 = C,51199120,36937872,14261248,0.73
Array2 =I,102398308,6240560,96157748,0.07
Array3 =J,90598564,1920184,88678380,0.03
Can Anybody help with Java code?
I don't think it's that simple. You have two things you need to do:
Break up the input string when you encounter a letter
Break up each substring by the pipe
I'm no regex expert, but I don't think it can be a single pattern. You need two and a loop over the substrings.
You can easily split your string on subcomponents using String.split("\\|"), but regexes won't help you to group them up in different arrays, nor will it help you to convert substrings to appropriate type. You'll need a separate logic for that.
Use String.split() method.
String []ar=str.split("(?=([A-Z]))");
for(String s:ar)
System.out.println(s.replace("|",","));
Simpler to just split then loop.
More or less:
String input = ...
String[] splitted = input.split("|");
List<String[]> resultArrays = new ArrayList<String[]>();
String[] currentArray = null;
for (int i = 0; i < splitted.length; i++) {
if (i % 5 == 0) {
currentArray = new String[5];
resultArrays.put(currentArray);
}
currentArray[i%5] = splitted[i];
}

Categories