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 "".
Related
This is my raw code
int n1=nextInt();
String ch=next().split("");
int n2=nextInt().split("");
if i want to get input line 5A11 (in same line).What should i do to get input like this.IS it possible to get input like this in java
Read the input as a String. Then use below code to remove the characters from the String followed by summing the integers.
String str = "123ABC4";
int sum = str.replaceAll("[\\D]", "")
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(sum);
You can use String#split.
int[] parseInput(String input) {
final String[] tokens = input.split("A"); // split the string on letter A
final int[] numbers = new int[tokens.length]; // create a new array to store the numbers
for (int i = 0; i < tokens.length; i++) { // iterate over the index of the tokens
numbers[i] = Integer.parseInt(tokens[i]); // set each element to the parsed integer
}
return numbers;
}
Now you can use it as
int[] numbers;
numbers = parseInput("5A11");
System.out.println(Arrays.toString(numbers)); // output: [5, 11]
numbers = parseInput("123A456");
System.out.println(Arrays.toString(numbers)); // output: [123, 456]
String input = "123C567";
String[] tokens = input.split("[A-Z]");
int first = Integer.parseInt(tokens[0]);
int second = Integer.parseInt(tokens[1]);
I have a string in java as
Input
String str = "1,2,3,11,#5,#7,9";
Output Desired
String result = "1,2,3,11,9";
// And 5,7 with special character # in separate Array-list
//List<String> list = ["5","7"];
Note: This special character # is dynamic, it may or may not be present in string.
I know how to remove # using str.replaceAll("#", "");, but how to get 5 and 7 in a separate list.
String str = "1,2,3,11,#5,#7,9";
List<String> parts = Arrays.asList(str.split(","));
List<Integer> normalNumbers = parts.stream().filter(i -> !i.startsWith("#")).map(Integer::parseInt).collect(
Collectors.toList());
List<Integer> specialNumbers = parts.stream().filter(i -> i.startsWith("#")).map(i -> Integer.valueOf(i.substring(1))).collect(Collectors.toList());
System.out.println(normalNumbers);
System.out.println(specialNumbers);
String in Java has a method called split(). You could easily use this to get all Integers with & without the prefix #
String str = "1,2,3,11,#5,#7,9";
List<Integer> res = Arrays.asList(str.split(",")).stream().map(ch->{
if(!ch.startsWith("#")){
return Integer.parseInt(ch);
}else {
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
System.out.println(res);
1. You could try String.split(),
String[] tokens = str.split(",");
2. Create 2 new String Array-List,
ArrayList<String> num = new ArrayList<String>();
ArrayList<String> result = new ArrayList<String>();
3. Then loop thru the tokens, checking each token, then push,
for(int i = 0; i < tokens.length; i++)
{
if(tokens[i].charAt(0) == '#')
num.add(String.valueOf(tokens[i].charAt(1)));
else
result.add(tokens[i]);
}
String str = "1,2,3,11,#5,#7,9";
List<String> s = Arrays.asList(str.split(",")).stream().filter(a->a.startsWith("#")).map(a->a.replace("#", "")).collect(Collectors.toList());
System.out.println(s); //Output [5, 7]
str = Arrays.asList(str.split(",")).stream().filter(a->!a.startsWith("#")).collect(Collectors.joining(","));
System.out.println(str); //Output 1,2,3,11,9
Suppose I have a string "1 23 40 187 298". This string only contains integers and spaces. How can I convert this string to an integer array, which is [1,23,40,187,298].
this is how I tried
public static void main(String[] args) {
String numbers = "12 1 890 65";
String temp = new String();
int[] ary = new int[4];
int j=0;
for (int i=0;i<numbers.length();i++)
{
if (numbers.charAt(i)!=' ')
temp+=numbers.charAt(i);
if (numbers.charAt(i)==' '){
ary[j]=Integer.parseInt(temp);
j++;
}
}
}
but it doesn't work, please offer some help. Thank you!
You are forgetting about
resetting temp to empty string after you parse it to create place for new digits
that at the end of your string will be no space, so
if (numbers.charAt(i) == ' ') {
ary[j] = Integer.parseInt(temp);
j++;
}
will not be invoked, which means you need invoke
ary[j] = Integer.parseInt(temp);
once again after your loop
But simpler way would be just using split(" ") to create temporary array of tokens and then parse each token to int like
String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];
int i = 0;
for (String token : tokens){
ary[i++] = Integer.parseInt(token);
}
which can also be shortened with streams added in Java 8:
String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
.mapToInt(token -> Integer.parseInt(token))
.toArray();
Other approach could be using Scanner and its nextInt() method to return all integers from your input. With assumption that you already know the size of needed array you can simply use
String numbers = "12 1 890 65";
int[] ary = new int[4];
int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
ary[i++] = sc.nextInt();
}
For java 8+ you can use this way:
final Integer[] ints = Arrays.stream(numbers.split(" "))
.map(Integer::parseInt)
.toArray(Integer[]::new);
or, if you need primitive ints, you can use this:
final int[] ints = Arrays.stream(numbers.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
Reset the tmp String to "" after you parse the integer unless you wish to continue to append all the numbers of the String together. There are also alternatives as well - for instance splitting the String into an array on the space characeter, and then parsing the numbers individually
Try this out,
public static void main(String[] args) {
String numbers = "12 1 890 65";
String[] parts = numbers.split(" ");
int[] ary = new int[4];
int element1 = Integer.parseInt(parts[0]);
int element2 = Integer.parseInt(parts[1]);
int element3 = Integer.parseInt(parts[2]);
int element4 = Integer.parseInt(parts[3]);
ary[0] = element1;
ary[1] = element2;
ary[2] = element3;
ary[3] = element4;
for(int i=0; i<4; i++){
System.out.println(ary[i]);
}
}
I met similar question in android development. I want to convert a long string into two array -String array xtokens and int array ytokens.
String result = "201 5 202 8 203 53 204 8";
String[] tokens = result.split(" ");
String[] xtokens = new String[tokens.length/2 + 1];
int[] ytokens = new int[tokens.length/2 + 1];
for(int i = 0, xplace = 0, yplace = 0; i<tokens.length; i++){
String temptoken = new String(tokens[i]);
if(i % 2 == 0){
xtokens[xplace++] = temptoken;
}else {
ytokens[yplace++] = Integer.parseInt(temptoken);
}
}
You can first convert this string into an string array separated by space, then convert it to int array.
I want to input a String like this "5 4 34" from keyboard. How can I export the numbers between spaces? Also a want to export them into an int[] array, and print them on the screen.
You can use String.split("\\s") to split the String to String[] and then use Integer.parseInt() on each element to get the number as an int.
Alternatively, you can use a Scanner, and its nextInt() method
Since the others have already showed you how it can be done with split(), here is an example how to do it with Scanner, directly from System.in (I am assuming that what you want, because you say you read it from keyboard, of course you can use any Readable or a String to build your Scanner):
Code:
Scanner inputScanner = new Scanner(System.in);
Scanner scanner = new Scanner(inputScanner.nextLine());
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Integer[] arr = list.toArray(new Integer[0]);
or if you want an int[] and not an Integer[] instead of the last line, use:
int[] arr = new int[list.size()];
int i = 0;
for (Integer x : list) {
arr[i++] = x;
}
To print the array just print the result of Arrays.toString():
System.out.println(Arrays.toString(arr));
Add an exception handler and you're in good shape:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
List<Integer> numbers = new ArrayList<Integer>();
for (String number : tokens) {
numbers.add(Integer.valueOf(number);
}
Or like this:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
int [] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
numbers[i] = Integer.valueOf(tokens[i]);
}
String string = "5 4 34";
String[] components = string.split(" "); // [5, 4, 34]
String[] stringArray = "5 4 34".split( " " );
int[] intArray = new int[ stringArray.length ];
for ( int i = 0 ; i < stringArray.length ; i++ )
{
intArray[ i ] = Integer.parseInt( stringArray[ i ] );
}
Without much boilerplate:
List <Integer> numbers = new ArrayList <Integer> ();
for (String number : "5 4 34";.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers.add (v);
}
Or using Scanner:
Scanner scanner = new Scanner ("5 4 34");
List <Integer> list = new ArrayList <Integer> ();
while (scanner.hasNextInt()) {
int v = scanner.nextInt ();
list.add (v);
System.out.println (v);
}
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]