I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?
String result=",17,18,19,";
First remove leading commas:
result = result.replaceFirst("^,", "");
If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):
String[] arr = result.split(",");
One liner:
String[] arr = result.replaceFirst("^,", "").split(",");
String[] myArray = result.split(",");
This returns an array separated by your argument value, which can be a regular expression.
Try split()
Assuming this as a fixed format,
String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
System.out.println(string);
}
//output : 17 18 19
That split() method returns
the array of strings computed by splitting this string around matches of the given regular expression
You can do like this :
String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
for(String resultArr:resultArray)
{
System.out.println(resultArr);
}
Related
In java I want to iterate an array to find any matching words from my input string
if the input string is appended to numbers it should return true.
Array arr = {"card","creditcard","debitcard"}
String inputStr = "need to discard pin" --> Return False
String inputStr = "need to 444card pin" --> Return True if its followed by number
I tried the below code, but it returns true as it takes "card" from the "discard" string and compares, but I need to do an exact match
Arrays.stream(arr).anymatch(inputString::contains)
Try this:
String[] arr = {"card","creditcard","debitcard"}; // array that keeps the words
String inputStr = "need to discard pin"; // String that keeps the 'sentence'
String[] wordsToBeChecked = inputStr.split(" "); // We take the string and split it at each " " (space)
HashSet<String> matchingWords = new HashSet<>(); // This will keep the matching words
for (String s : arr)
{
for (String s1 : wordsToBeChecked)
{
if(s.equalsIgnoreCase(s1)) // If first word matches with the second
{
matchingWords.add(s1); // add it to our container
}
}
}
Or using Java 8 Streams:
List<String> wordList = Arrays.asList(arr);
List<String> sentenceWordList = Arrays.asList(inputStr.split(" "));
List<String> matchedWords = wordList.stream().filter(sentenceWordList::contains)
.collect(Collectors.toList());
The problem with most answers here is that they do not take punctuation into consideration. To solve this, you could use a regular expression like below.
String[] arr = { "card", "creditcard", "debitcard" };
String inputStr = "You need to discard Pin Card.";
Arrays.stream(arr)
.anyMatch(word -> Pattern
.compile("(?<![a-z-])" + Pattern.quote(word) + "(?![a-z-])", Pattern.CASE_INSENSITIVE)
.matcher(inputStr)
.find());
With Pattern.quote(word), we escape any character within each word with is a special character in the context of a regular expression. For instance, the literal string a^b would never match, because ^ means the start of a string if used in a regular expression.
(?<![a-z-]) and (?![a-z-]) mean that there is not a word character immediately preceding or succeeding the word. For instance, discard will not match, even if it contains the word card. I have used only lowercase in these character classes because of the next bullet:
The flag CASE_INSENSITIVE passed to the compile method causes the pattern to be matched in a case-insensitive manner.
Online demo
You could split the string using a regular expression
String[] arr = {"card","creditcard","debitcard"};
String inputStr = "need to discard pin";
List<String> wordsToBeChecked = Arrays.asList(inputStr.split("[ 0-9]"));
Arrays.stream(arr).anyMatch(wordsToBeChecked::contains);
If your word list and input string is longer, consider splitting your input string into a hashset. Looksups will be faster, then:
Set<String> wordsToBeChecked = new HashSet<>(Arrays.asList(inputStr.split(" ")));
You can create a Set of the words in inputStr and then check the words list against that Set.
Set<String> inputWords = uniqueWords(inputStr);
List<String> matchedWords = Arrays.stream(arr)
.anyMatch(word -> inputWords.contains(word))
.collect(Collectors.toList());
Building the Set may be non-trivial if you have to account for hyphenation, numbers, punctuation, and so forth. I'll wave my hands and ignore that - here's a naive implementation of uniqueWords(String) that assumes they are separated by spaces.
public Set<String> uniqueWords(String string) {
return Arrays.stream(string.split(" "))
.collect(Collectors.toSet());
}
One way would be
String[] arr = {"card","creditcard","debitcard"};
String inputStr = "need to discard pin";
var contains = Arrays.stream(inputStr.split(" ")).anyMatch(word -> Arrays.asList(arr).contains(word));
You can adjust the split regex to include all kinds of whitespace too.
Also: Consider an appropriate data structure for lookups. Array will be O(n), HashSet will be O(1).
I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});
I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3
Given the following string:
423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
I would like to split it and put the contents in a array excluding the square brackets and the numbers in the brackets - i.e the result should be an array that contains the following.
{423545,7568787,53654656,2021947,021947,2021947,8021947}
My attempt so far only works if there are no square brackets:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.split("(\\(\\d+\\))?(?:,|$)")
How can I update the above regex to also extract the numbers that wrapped in square brackets?
The strings I am trying to extract are identifiers for database rows so i need to extract them to retrieve the database row.
You could try this way
String str = "[342398789], [233434] ,423545(50),[7568787(500)],"
+ "53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceFirst("^\\[", "").split(
"(\\(\\d+\\))?\\]?(\\s*,\\s*\\[?|$)");
System.out.println(Arrays.toString(listItems));
output
[342398789, 233434, 423545, 7568787, 53654656, 2021947, 021947, 2021947, 8021947]
try this way:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceAll("\\(\\d+\\)","")replaceAll("\\[","").replaceAll("\\]","").split(",");
I have a string = "name";
I want to convert into a string array.
How do I do it?
Is there any java built in function? Manually I can do it but I'm searching for a java built in function.
I want an array where each character of the string will be a string.
like char 'n' will be now string "n" stored in an array.
To start you off on your assignment, String.split splits strings on a regular expression and this expression may be an empty string:
String[] ary = "abc".split("");
Yields the array:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
Note: In Java 8, the empty first element is no longer included.
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"
The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:
String[] strArray = new String[1];
instead, the length is determined by the number of elements in the initalizer. Using
String[] strArray = new String[] {strName, "name1", "name2"};
creates an array with a length of 3.
I guess there is simply no need for it, as it won't get more simple than
String[] array = {"name"};
Of course if you insist, you could write:
static String[] convert(String... array) {
return array;
}
String[] array = convert("name","age","hobby");
[Edit]
If you want single-letter Strings, you can use:
String[] s = "name".split("");
Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.
Assuming you really want an array of single-character strings (not a char[] or Character[])
1. Using a regex:
public static String[] singleChars(String s) {
return s.split("(?!^)");
}
The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.
2. Using Guava:
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
// ...
public static String[] singleChars(String s) {
return
Lists.transform(Chars.asList(s.toCharArray()),
Functions.toStringFunction())
.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
In java 8, there is a method with which you can do this: toCharArray():
String k = "abcdef";
char[] x = k.toCharArray();
This results to the following array:
[a,b,c,d,e,f]
String data = "abc";
String[] arr = explode(data);
public String[] explode(String s) {
String[] arr = new String[s.length];
for(int i = 0; i < s.length; i++)
{
arr[i] = String.valueOf(s.charAt(i));
}
return arr;
}
Simply use the .toCharArray() method in Java:
String k = "abc";
char[] alpha = k.toCharArray();
This should work just fine in Java 8.
String array = array of characters ?
Or do you have a string with multiple words each of which should be an array element ?
String[] array = yourString.split(wordSeparator);
Convert it to type Char?
http://www.javadb.com/convert-string-to-character-array
You could use string.chars().mapToObj(e -> new String(new char[] {e}));, though this is quite lengthy and only works with java 8. Here are a few more methods:
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
The last one is just unnecessarily long, it's just for fun!
An additional method:
As was already mentioned, you could convert the original String "name" to a char array quite easily:
String originalString = "name";
char[] charArray = originalString.toCharArray();
To continue this train of thought, you could then convert the char array to a String array:
String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
stringArray[i] = String.valueOf(charArray[i]);
}
At this point, your stringArray will be filled with the original values from your original string "name".
For example, now calling
System.out.println(stringArray[0]);
Will return the value "n" (as a String) in this case.
here is have convert simple string to string array using split method.
String [] stringArray="My Name is ABC".split(" ");
Output
stringArray[0]="My";
stringArray[1]="Name";
stringArray[2]="is";
stringArray[3]="ABC";
Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).
import org.apache.commons.lang3.StringUtils;
StringUtils.split(null) => null
StringUtils.split("") => []
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split(" abc ") => ["abc"]
Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:
import com.google.common.base.Splitter;
Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
SPLITTER.split("a,b, c , , ,, ") => [a, b, c]
SPLITTER.split("") => []
SPLITTER.split(" ") => []
SPLITTER.split(null) => NullPointerException
If you want a list rather than an iterator then use Splitter.splitToList().
/**
* <pre>
* MyUtils.splitString2SingleAlphaArray(null, "") = null
* MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
* </pre>
* #param str the String to parse, may be null
* #return an array of parsed Strings, {#code null} if null String input
*/
public static String[] splitString2SingleAlphaArray(String s){
if (s == null )
return null;
char[] c = s.toCharArray();
String[] sArray = new String[c.length];
for (int i = 0; i < c.length; i++) {
sArray[i] = String.valueOf(c[i]);
}
return sArray;
}
Method String.split will generate empty 1st, you have to remove it from the array. It's boring.
Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.
This makes an array of words by splitting the string at every space:
String str = "string to string array conversion in java";
String delimiter = " ";
String strArray[] = str.split(delimiter);
This creates the following array:
// [string, to, string, array, conversion, in, java]
Source
Tested in Java 8