Java Split String with Numbers - java

How do I split a string with numbers?
Like if I have "20 40" entered, how do I split
it so I get 20, 40?
int t = Integer.parseInt(x);
int str = t;
String[] splited = str.split("\\s+");
My code.

If you're trying to parse a string that contains whitespace-delimited integer tokens, into an int array, the following will work:
String input = "20 40";
String[] tokens = input.split(" ");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i].trim());
}
You can also do this in a one-liner through the Iterables and Splitter utilities from the amazing Google Guava library:
Integer[] numbers = Iterables.toArray(Iterables.transform(
Splitter.on(' ').trimResults().split(input),
new Function<String, Integer>() {
#Override
public Integer apply(String token) {
return Integer.parseInt(token);
}
}), Integer.class);

You need to convert it to String value and then split, maybe like this:
String[] splited = String.valueOf(str).split("\\s+");
It seems you are reading the number as String and trying to convert it to integer before the split here:
int t = Integer.parseInt(x);
so you can actually split your variable x and get the indiviudal int values out of it like this:
String[] splited = x.split("\\s+");
for(String num:splited) {
int intVal = Integer.valueOf(num);
}

Related

How to split an array of strings whose indexes contain integers and letters Java

Hi guys! =)
I'm new to Java, currently, I'm learning arrays and loops. I have an interesting homework task that I am very confused about.
And I don't know what to do with this one. So I need your advice.
Create a public String getCheapStocks(String[] stocks) method in it. It takes an array of strings as input. Each line consists of the name of the product and its price, separated by a single space.
The method returns a string - a list of product names whose price is less than 200.
And the getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}) returns "firebow".
There is only for loop can be used.
I found a method that can split a string:
String text = "123 456"
String[] parts = text.split(" ")
int number1 = Integer.parseInt(parts[0]) //123
int number2 = Integer.parseInt(parts[1]) //456
But when I have String "gun 500" I can only split it in two String. And I can't compare it to 200. My code is a mess and it does nothing.
I would really appreciate any tips or advice, thanks in advance!
public static String getCheapStocks(String[] stocks) {
//MESS!
int max = 200;
for(int i = 0; i < stocks.length; i++) {
String txt = stocks[i];
String[] parts = txt.split(" ");
int number1 = Integer.parseInt(parts[0]);
int number2 = Integer.parseInt(parts[1]);
if(number1 < max) {
}
}
}
public static void main(String[] args) {
//returns "firebow"
System.out.println(getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}));
}
}
Since your input is in format of "<stock> <price>", after splitting this into 2 parts, you have to convert only the second part to an integer, otherwise you will get an exception.
public static String getCheapStocks(String[] stocks) {
// Use a StringBuilder to hold the final result
StringBuilder result = new StringBuilder();
for (String stock : stocks) {
String[] parts = stock.split(" ");
// If the price is lower than 200, append part[0] (stock name) to the result
if (Integer.parseInt(parts[1]) < 200) {
result.append(parts[0]).append(" "); // Append also a space character for dividing the stocks
}
}
// Strip the space from the end
return result.toString().trim();
}
public static String getCheapStocks(String[] stocks) {
int maxPrice = 200;
List<String> results = new ArrayList<>();
for (String txt : stocks) {
String[] parts = txt.split(" ");
String stockName = parts[0];
int price = Integer.parseInt(parts[1]);
if (price < maxPrice) {
results.add(stockName);
}
}
return String.join(" ", results);
}

JAVA : String Manipulation using Split function

I have a string "AB12TRHW4TR6HH58", i need to split this string and whenever i find a number, i need to perform addition of all. However, if there are consecutive numbers then i need to take it as a whole number.
For example, in above string the addition should be done like 12+4+6+58 and so on.
I written below code which adds all numbers individually but cant take a whole number. Could you please help?
public class TestClass {
public static void main(String[] args) {
String str = "AB12TRHW4TR6HH58";
int len = str.length();
String[] st1 = str.split("");
int temp1=0;
for(int i=0;i<=len-1;i++){
if(st1[i].matches("[0-9]")){
int temp = Integer.parseInt(st1[i]);
temp1 = temp+temp1;
}
}
System.out.println(temp1);
}
}
Doing what I said in my comment:
String str = "AB12TRHW4TR6HH58";
String[] r = str.split("[a-zA-Z]");
int sum = 0;
for ( String s : r ) {
if ( s.length() > 0 ) {
sum += Integer.parseInt(s);
}
}
System.out.println(sum);
You can split on non-numeric characters and use the resulting array:
String[] st1 = "AB12TRHW4TR6HH58".split("[^0-9]+");
int temp1 = 0;
for (int i = 0; i < st1.length; i++) {
if (st1[i].isEmpty()) {
continue;
}
temp1 += Integer.parseInt(st1[i]);
}
System.out.println(temp1);
And it can even be simplified further using a stream:
int temp1 = Stream.of(st1)
.filter(s -> !s.isEmpty())
.mapToInt(Integer::new)
.sum();
Instead of splitting around the parts you want to omit, just search what you need: the numbers. Using a Matcher and Stream we can do this like that:
String str = "AB12TRHW4TR6HH58";
Pattern number = Pattern.compile("\\d+");
int sum = number.matcher(str)
.results()
.mapToInt(r -> Integer.parseInt(r.group()))
.sum();
System.out.println(sum); // 80
Or with an additional mapping but using only method references:
int sum = number.matcher(str)
.results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt)
.sum();

How do I split a string into even parts then populate an array with those new strings?

I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);

Java how to parse integers with spaces

I have a string, actually user put in console next string :
10 20 30 40 50
how i can parse it to int[] ?
I tried to use Integer.parseInt(String s); and parse string with String.indexOf(char c) but i think it's too awful solution.
You could use a Scanner and .nextInt(), or you could use the .split() command on the String to split it into an array of Strings and parse them separately.
For example:
Scanner scanner = new Scanner(yourString);
ArrayList<Integer> myInts = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
myInts.add(scanner.nextInt());
}
For the split:
String[] intParts = yourString.split("\\s+");
ArrayList<Integer> myInts = new ArrayList<Integer>();
for (String intPart : intParts) {
myInts.add(Integer.parseInt(intPart));
}
Split the String, using the String#split() method with the delimiter space.
For each element in the String[], parse it into an int using Integer.parseInt() and add them to your int[].
String split[] = string.split(" ")
is will generate an array of string then you can parse the array to int.
Split the string then parse the integers like the following function:
int[] parseInts(String s){
String[] sNums = s.split(" ");
int[] nums = new int[sNums.length];
for(int i = 0; i < sNums.length; i++){
nums[i] = Integer.parseInt(sNums[i);
}
return nums;
}

How to separate out int values from a string?

I have a variable of type StringBuffer which has certain numbers in it say,
StringBuffer newString = new StringBuffer("25 75 25");
Now if I want to separate this out in an integer array, how could i do it?
for(int i=0;i<numberOfItemsInTheStore;i++){
newString.append(values.charAt(0));
values.deleteCharAt(0);
char c = values.charAt(0);
if(c==' ' || values.length()==1){
values.deleteCharAt(0);
value[i] = Integer.parseInt(newString.toString());
newString.delete(0, newString.length());
System.out.println(value[i]);
}
}
What might be wrong in the program?
String[] splits = newString.toString().split(" ");
int[] arrInt = new int[splits.length];
int idx = 0;
for (String s: splits){
arrInt[idx++] = Integer.parseInt(s);
}
You can get String array easily and when you want to use elements as int values use Integer.parseInt() method
StringBuffer newString = new StringBuffer("25 75 25");
String [] strArr = newString.toString().split(" ");
System.out.println(Arrays.toString(strArr));

Categories

Resources