Using String.split() to access numeric values - java

i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing

String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)

First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).

String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9

public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.

Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}

String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));

I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}

I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]

Related

Java, extract integer values within defined characters from long string

I have a program where I receive a long string in the format
characters$xxx,characters$xx,characters$xx, (....)
x is some digit of some integer with an arbitrary number of digits. The integer values are always contained within $ and ,.
I need to extract the integers into an integer array then print that array. The second part is easy, but how to extract those integers?
an example string: adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623,
the arraay should contain 1234, 356, 98, 4623
below is my basic logic
import java.util.Scanner;
class RandomStuff {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
int count =0;
// counts number of $, because $ will always preceed an int in my string
for(int i=0;i<input.length();i++ ){
if (input.charAt(i)=='$')
count++;}
/* also I'm traversing the string twice here so my complexity is at least
o(2n) if someone knows how to reduce that, please tell me*/
int [] intlist = new int[count];
// fill the array
int arrayindex =0;
for (int i=0; i<input.length();i++){
if (input.charAt(i)=='$'){
/*insert all following characters as a single integer in intlist[arrayindex]
until we hit the character ','*/}
if (input.charAt(i)==','){
arrayindex++;
/*stop recording characters*/}
}
// i can print an array so I'll just omit the rest
keyboard.close();
}
You can use a regular expression with a positive lookbehind to find all consecutive sequences of digits preceded by a $ symbol. Matcher#results can be used to get all of the matches.
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
int[] nums = Pattern.compile("(?<=\\$)\\d+").matcher(str).results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(nums));
It can done like this
var digitStarts = new ArrayList<Integer>()
var digitsEnds = new ArrayList<Integer>()
// Get the start and end of each digit
for (int i=0; i<input.length();i++){
if(input[i] == '$' ) digitsStarts.add(i)
if(input[i] == ',') digitEnds.add(i)
}
// Get the digits as strings
var digitStrings = new ArrayList<String>()
for(int i=0;i<digitsStart.length; i++ ) {
digitsString.add(input.substring(digitsStarts[i]+1,digitEnds[i]))
}
// Convert to Int
var digits = new ArrayList<Int>
for(int i=0;i<digitString;i++) {
digits.add(Integer.valueOf(digitStrings[i]))
}
In a very simple way:
public static void main(String[] args) {
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
String strArray[] = str.split(",");
int numbers[] = new int[strArray.length];
int j = 0;
for(String s : strArray) {
numbers[j++] = Integer.parseInt(s.substring(s.indexOf('$')+1));
}
for(j=0;j<numbers.length;j++)
System.out.print(numbers[j]+" ");
}
OUTPUT: 1234 356 98 4623

Returning a String Array

import java.util.Random;
import java.util.Scanner;
public class ArrayHelpers{
public static void main(String[] args){
String arr[] = {"M3", "M4", "M5", "M6", "X5M", "M750Li"};
String stockElements[] = {"BMW M2 Coupé","BMW M3 Sedan", "BMW M4 Coupé", "BMW M5 Sedan","BMW M6 Gran Coupé", "BMW X5 M", "BMW X6 M", "M 750Li"};
int size = 7;
printArrayQuantities(arr);
System.out.println(getRandomElement(arr));
System.out.println(getRandomArray(size, stockElements));
}
public static void printArrayQuantities(String[] arr){
int num[] = {2, 1, 3, 3, 5, 1};
for( int i = 0; i < num.length; i++){
System.out.println(arr[i] + " " + num[i]);
}
}
public static String getRandomElement(String[] arr){
int randomNum = 0 + (int)(Math.random() * 6);
return arr[randomNum];
}
public static String[] getRandomArray(int size, String[] stockElements){
String[] randArray = new String[size];
for( int i = 0; i < size; i++){
randArray[i] = getRandomElement(stockElements);
}
return randArray;
}
}
So I'm trying to return an array that has been randomly inserted with elements from stockElements through getRandomElement method. When I'm trying to print that array from line 12 (System.out.println(getRandomArray(size, stockElements));) it produces [Ljava.lang.String;#6d06d69c as output. I'm aware of the .toString() method, but a requirement of my assignment is that I do not use any built in array methods. How exactly would I go about doing this?
A simple solution is just to iterate over it with for each loop.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(String str : myArray){
System.out.println(str);
}
or with for loop if you prefer.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
Since your function is returning an array, when you try to print the array you should be iterating through each elements with a for/while loop and printing them individually. Since you're trying to print the array variable it instead prints java's handle for it. So try something like this
String[] randomArray = getRandomArray(size, stockElements);
for (String s : randomArray) {
System.out.println(s);
}
Replace System.out.println(getRandomArray(size, stockElements)); with
String [] output = getRandomArray(size, stockElements);
printArrayQuantities(output);
You already have the array returned, just need to assign it:
String[] newArray = getRandomArray(size, stockElements);
But... if you want to just print it go with the below.
Using Java 8:
String.join(delimiter, newArray);
or (for older Java):
StringBuilder builder = new StringBuilder();
for(String s : newArray) {
builder.append(s);
builder.append(delimeter);
}
return builder.toString();

JTextField to int[] array?

I'm working on my graphic user interface for a application I'm creating. Basically there is this JTextField that the user has to input integers. For example
25, 50, 80, 90
Now, I have this other class that needs to get those values and put them in an int Array.
I've tried the following.
guiV = dropTheseText.getText().split(",");
And in the other class file I retieve the String, but I have no idea how to get the value for each one.
In the end I'm just trying to get something like
int[] vD = {textfieldvaluessplitbycommahere};
Still fairly new to Java but this has me crazy.
private JTextField txtValues = new JTextField("25, 50, 80, 90");
// Strip the whitespaces using a regex since they will throw errors
// when converting to integers
String values = txtValues.getText().replaceAll("\\s","");
// Get the inserted values of the text field and use the comma as a separator.
// The values will be returned as a string array
private String[] strValues = values.split(",");
// Initialize int array
private int[] intValues = new int[strValues.length()];
// Convert each string value to an integer value and put it into the integer array
for(int i = 0; i < strValues.length(); i++) {
try {
intValues[i] = Integer.parseInt(strValues[i]);
} catch (NumberFormatException nfe) {
// The string does not contain a parsable integer.
}
}
As you are fairly new to Java, rather than giving you the code snippet, I will just give you some indications:
Use the String class: it has a method for splitting a String into an array of Strings.
Then use the Integer class: it has a method to convert a String to an int.
You cant do it directly, you may need to add a method to convert your string array to int array. Something like this:
public int[] convertStringToIntArray(String strArray[]) {
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
Pass your guiV to this method and get back the int array
a simple solution is a function hat does the conversion:
public static int[] convertTextFieldCommaSeparatedIntegerStringToIntArray(String fieldText) {
String[] tmp = fieldText.split(",");
int[] result = new int[tmp.length];
for(int i = 0; i < tmp.length; i++) {
result[i] = Integer.parseInt(tmp[i].trim());
}
return result;
}
The essential methods are:
split for splitting the original input at the comma.
parseInt for converting a String -> int. The valueOf function of Integer is an option but then you have to convert String -> Integer -> int.
Note:
You should use trim to eliminate white-spaces. Furthermore, you should catch the NumberFormatException thrown by parseInt. As an unchecked exception you do not need to catch it, but it is always wise to check user input and sanitize it if necessary.
Try this code:
public int[] getAsIntArray(String str)
{
String[] values = str.getText().split(",");
int[] intValues = new int[values.length];
for(int index = 0; index < values.length; index++)
{
intValues[index] = Integer.parseInt(values[index]);
}
return intValues;
}

How to get list of Integer from String

my string contains Integer separated by space:
String number = "1 2 3 4 5 "
How I can get list of Integer from this string ?
You can use a Scanner to read the string one integer at a time.
Scanner scanner = new Scanner(number);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
ArrayList<Integer> lst = new ArrayList<Integer>();
for (String field : number.split(" +"))
lst.add(Integer.parseInt(field));
With Java 8+:
List<Integer> lst =
Arrays.stream(number.split(" +")).map(Integer::parseInt).collect(Collectors.toList());
String number = "1 2 3 4 5";
String[] s = number.split("\\s+");
And then add it to your list by using Integer.parseInt(s[index]);
List<Integer> myList = new List<Integer>();
for(int index = 0 ; index<5 ; index++)
myList.add(Integer.parseInt(s[index]);
In Java 8 you can use streams and obtain the conversion in a more compact way:
String number = "1 2 3 4 5 ";
List<Integer> x = Arrays.stream(number.split("\\s"))
.map(Integer::parseInt)
.collect(Collectors.toList());
Using Java8 Stream API map and mapToInt function you can archive this easily:
String number = "1 2 3 4 5";
List<Integer> x = Arrays.stream(number.split("\\s"))
.map(Integer::parseInt)
.collect(Collectors.toList());
or
String stringNum = "1 2 3 4 5 6 7 8 9 0";
List<Integer> poolList = Arrays.stream(stringNum.split("\\s"))
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
Firstly,using split() method to make the String into String array.
Secondly,using getInteger() method to convert String to Integer.
String number="1 2 3 4 5";
List<Integer> l=new ArrayList<Integer>();
String[] ss=number.split(" ");
for(int i=0;i<ss.length;i++)
{
l.add(Integer.parseInt(ss[i]));
}
System.out.println(l);
Simple solution just using arrays:
// variables
String nums = "1 2 3 4 5";
// can split by whitespace to store into an array/lits (I used array for preference) - still string
String[] num_arr = nums.split(" ");
int[] nums_iArr = new int[num_arr.length];
// loop over num_arr, converting element at i to an int and add to int array
for (int i = 0; i < num_arr.length; i++) {
int num_int = Integer.parseInt(num_arr[i])
nums_iArr[i] = num_int
}
That pretty much covers it. If you wanted to output them, to console for instance:
// for each loop to output
for (int i : nums_iArr) {
System.out.println(i);
}
I would like to introduce tokenizer class to split by any delimiter. Input string is scanned only once and we have a list without extra loops.
String value = "1, 2, 3, 4, 5";
List<Long> list=new ArrayList<Long>();
StringTokenizer tokenizer = new StringTokenizer(value, ",");
while(tokenizer.hasMoreElements()) {
String val = tokenizer.nextToken().trim();
if (!val.isEmpty()) list.add( Long.parseLong(val) );
}
split it with space, get an array then convert it to list.
You can split it and afterwards iterate it converting it into number like:
String[] strings = "1 2 3".split("\\ ");
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
System.out.println(Arrays.toString(ints));
You first split your string using regex and then iterate through the array converting every value into desired type.
String[] literalNumbers = [number.split(" ");][1]
int[] numbers = new int[literalNumbers.length];
for(i = 0; i < literalNumbers.length; i++) {
numbers[i] = Integer.valueOf(literalNumbers[i]).intValue();
}
I needed a more general method for retrieving the list of integers from a string so I wrote my own method.
I'm not sure if it's better than all the above because I haven't checked them.
Here it is:
public static List<Integer> getAllIntegerNumbersAfterKeyFromString(
String text, String key) throws Exception {
text = text.substring(text.indexOf(key) + key.length());
List<Integer> listOfIntegers = new ArrayList<Integer>();
String intNumber = "";
char[] characters = text.toCharArray();
boolean foundAtLeastOneInteger = false;
for (char ch : characters) {
if (Character.isDigit(ch)) {
intNumber += ch;
} else {
if (intNumber != "") {
foundAtLeastOneInteger = true;
listOfIntegers.add(Integer.parseInt(intNumber));
intNumber = "";
}
}
}
if (!foundAtLeastOneInteger)
throw new Exception(
"No matching integer was found in the provided string!");
return listOfIntegers;
}
The #key parameter is not compulsory. It can be removed if you delete the first line of the method:
text = text.substring(text.indexOf(key) + key.length());
or you can just feed it with "".

Convert String to int array in java

I have one string:
String arr = "[1,2]";
ie "[1,2]" is like a single String.
How do I convert this arr to int array in java?
String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Using Java 8's stream library, we can make this a one-liner (albeit a long line):
String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).
final String[] strings = {"1", "2"};
final int[] ints = new int[strings.length];
for (int i=0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:
String arr = "[1,2]";
JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");
int[] outArr = new int[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
outArr[i] = jsonArray.getInt(i);
}
Saul's answer can be better implemented splitting the string like this:
string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");
try this one, it might be helpful for you
String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
You can do it easily by using StringTokenizer class defined in java.util package.
void main()
{
int i=0;
int n[]=new int[2];//for integer array of numbers
String st="[1,2]";
StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
String s[]=new String[2];//for String array of numbers
while(stk.hasMoreTokens())
{
s[i]=stk.nextToken();
n[i]=Integer.parseInt(s[i]);//Converting into Integer
i++;
}
for(i=0;i<2;i++)
System.out.println("number["+i+"]="+n[i]);
}
Output :-number[0]=1
number[1]=2
String str = "1,2,3,4,5,6,7,8,9,0";
String items[] = str.split(",");
int ent[] = new int[items.length];
for(i=0;i<items.length;i++){
try{
ent[i] = Integer.parseInt(items[i]);
System.out.println("#"+i+": "+ent[i]);//Para probar
}catch(NumberFormatException e){
//Error
}
}
If you prefer an Integer[] instead array of an int[] array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.
The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.
public static void readToArray(String line, int[] resultArray) {
int index = 0;
int number = 0;
for (int i = 0, n = line.length(); i < n; i++) {
char c = line.charAt(i);
if (c == ',') {
resultArray[index] = number;
index++;
number = 0;
}
else if (Character.isDigit(c)) {
int digit = Character.getNumericValue(c);
number = number * 10 + digit;
}
}
if (index < resultArray.length) {
resultArray[index] = number;
}
}
public static int[] toArray(String line) {
int[] result = new int[countOccurrences(line, ',') + 1];
readToArray(line, result);
return result;
}
public static int countOccurrences(String haystack, char needle) {
int count = 0;
for (int i=0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle) {
count++;
}
}
return count;
}
countOccurrences implementation was shamelessly stolen from John Skeet
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

Categories