getting substrings in each array index using a delimeter - java

given an array
String original[]={"string0,10","string1,45","string2,3", "string3,67"};
how would I use the comma as a delimeter to create another array with only the names?
I need an array that looks something like this:
String result[]={"string0","string1","string2", "string3"};

You can use streams and map from java 8 to do it:
String[] strings = Arrays.stream(test)
.map(string -> string.split(",")[0])
.toArray(String[]::new);

public static void main(String[] args) {
String original[]={"string0,10","string1,45","string2,3", "string3,67"};
int len = original.length;
String result[] = new String[len];
for(int i=0; i<len;i++) {
result[i] = original[i].split(",")[0];
}
System.out.println(Arrays.toString(result));
}
DeclareString result[] array
Iterate the array
Split the record for every Iteration using , as delimiter
Now the split operation will return the array of size 2. It contains name at index 0.
assign the value the result array.

import java.util.Arrays;
import java.util.stream.Collectors;
public class ArraySubstring {
public static void main (String args[]) {
String test[]={"string0,10","string1,45","string2,3", "string3,67"};
String test2[] = Arrays.stream(test).map(s -> s.substring(0, s.indexOf(","))).toArray(String[]::new);
for (String s : test2) {
System.out.println(s);
}
}
}

Related

How to add character amounts in an array?

So I have an array of strings and need to take the amount of characters in each string and add them together to get 1 total. How would I go about doing this?
Here is the array:
public class Final21 {
public static String getLongString(String[] array) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
}
}
I am not adding indexes, but the amount of characters in each string.
Example: bob has 3 characters, tomtomjack has 10 characters, if you add them it would be 13
Attempts:
public static int countAllLetters(String[] array) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
Gives error:
Final21.java:62: error: unreachable statement
int amountOfLetters = countAllLetters(names);
^
Final21.java:65: error: missing return statement
}
^
2 errors
Using the stream API, it can be done as follows:
int sum = Arrays.stream(names)
.mapToInt(String::length)
.sum();
For a Java 8+ solution, refer to this answer by Aominè.
In the comments, you say you can't use Java 8. This answer exposes a solution for pre-Java 8 environments.
If you want to return an int containing the combined amount of characters from every String in the array, you need to change the return type of your method.
public static int countAllLetters(String[] array)
Notice how I changed the name to better express the behavior of this method.
To implement it, simply loop through the array and add together the length() of each String:
public static int countAllLetters(String[] array) {
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
}
This would be used as:
public static void main(String[] args) {
String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
So your finished result would be:
public class YourClass {
public static void main(String[] args) {
String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
public static int countAllLetters(String[] array) {
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
}
}
Click here to test using an online compiler
Also notice how I don't declare the names array inside the method. Instead, I declared it outside of the array, then passed it into the method as an argument. This allows the method to be reusable for different arrays, rather than a single hard-coded names array.
However, if you want to return a String of array's content combined (based on the name & return type you're showing in your question), you need to keep the return type of your method as String, and concat the items from the array:
public static String concat(String[] array) {
StringBuilder builder = new StringBuilder();
for(String s : array)
builder.append(s);
return builder.toString();
}

How can I take a part of a string and sort it in reverse alphabetical order? [duplicate]

This question already has answers here:
Sort a single String in Java
(13 answers)
Closed 6 years ago.
I want to achieve something like this:
String str = "Good Morning;
String subStr = str.substring(0,7);
Then I want to sort the letters in reverse order.
I want my output to be: ooMGd
A simple way:
String str = "Good Morning";
String subStr=str.substring(0,7);
char[] arr = subStr.toCharArray();
Arrays.sort(arr);
for(int i = arr.length - 1; i >= 0; i--)
System.out.print(arr[i]);
Why don't you use a StringBuilder object?
Try this one-liner: (new StringBuilder(str.substring(0, 7))).reverse().toString();
And the complete example (including the sorting):
package testing.project;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str = "Good Morning";
char[] sorted = new StringBuilder(str.substring(0, 7)).reverse().toString().toCharArray();
Arrays.sort(sorted);
String reversedString = new StringBuilder(new String(sorted)).reverse().toString();
System.out.println(reversedString);
}
}
Try -
public static void main(String[] args) throws IOException
{
String str="Good Morning;" ;
String[] subStr=str.substring(0,7).split("");
Arrays.sort(subStr,Collections.reverseOrder());
String s ="";
for(int i=0;i<subStr.length;i++)
{
s+=subStr[i];
}
System.out.println(s);
}
Create a String array of from sub-string and sort that collection in reverse order. You have a reverse order sorted array of string now append them to a string you have a string with desired result.
Or A better Solution will be StringBuilder
String str = "Good Morning";
String s = new StringBuilder(str.substring(0, 7)).reverse().toString();
System.out.println(s);
This will Also work correct.

How to remove last 3 characters from a list of String in java?

I have a list which contains some String in this format 23:45:50 ,12:32:70 etc. I want to cut this last two digits after :.
I am using substring() but it is not working properly,I am posting my code:
public class SplitString {
public static void main(String[] args) {
List<String> aList = new ArrayList<String>();
aList.add("4:78:34");
aList.add("5:8:34");
aList.add("8:18:90");
aList.add("2:8:40");
for(int i=0;i<aList.size();i++){
String str = aList.get(i).substring(0, aList.get(i).length()-3);
aList.add(str);
}
System.out.println(aList);
}
}
But giving the result
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(Unknown Source)
at com.test.SplitString.main(SplitString.java:19)
I want the output as 23:45,12:32
I think you should create a new list to storage the sub string. Do you know when your for-cycle break? I debugged it and get that it will break when your alist.size()=0. The exception causes when the aList.get(i).length()<3. So you just do like this:
`
List<String> aList = new ArrayList<String>();
aList.add("4:78:34");
aList.add("5:8:34");
aList.add("8:18:90");
aList.add("2:8:40");
List<String> subList = new ArrayList<String>();
for (int i = 0; i < aList.size(); i++)
{
String str = aList.get(i).substring(0, aList.get(i).length() - 3);
subList.add(str);
}
System.out.println(subList);`
I worked up a recursive function for you to call to get the string after the right most colon. So if you can find another colon, it keeps looking further. If it can't it returns what's left.
public static String getRight(String str) {
if (str.indexOf(':') > 0) {
str = getRight(str.substring(str.indexOf(':')+1));
}
return str;
}
As PM 77-1 said, you are adding more items to your list so it can't ever get to the end of the list. You need to store the original count if you are to ever get out of your for loop. Here is your fully modified code tested and working:
public class SplitString {
public static void main(String[] args) {
List<String> aList = new ArrayList<String>();
aList.add("4:78:34");
aList.add("5:8:34");
aList.add("8:18:90");
aList.add("2:8:40");
int original_size = aList.size();
for(int i=0;i<original_size;i++){
String str = aList.get(i);
aList.add(getRight(str));
}
System.out.println(aList);
}
public static String getRight(String str) {
if (str.indexOf(':') > 0) {
str = getRight(str.substring(str.indexOf(':')+1));
}
return str;
}
}
In Java 8:
aList = aList.stream().map(w -> w.substring(0, w.length()-3)).collect(Collectors.toList());

Converting a String array into an int Array in java

I am new to java programming. My question is this I have a String array but when I am trying to convert it to an int array I keep getting
java.lang.NumberFormatException
My code is
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
intarray[i]=Integer.parseInt(str);//Exception in this line
i++;
}
}
Any help would be great thanks!!!
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next ▼:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
▼ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
  1. Lambda Expressions in The Java Tutorials.
  2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Since you are trying to get an Integer[] array you could use:
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
Your code:
private void processLine(String[] strings) {
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}
Note, that this only works for Java 8 and higher.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number
separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
public static int[] strArrayToIntArray(String[] a){
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
return b;
}
This is a simple function, that should help you.
You can use him like this:
int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}

Sort String "13,5,8,4,2,1,9" in ascending order 1,2,4,5,8,9,13 in Java

How can I sort a string "13,5,8,4,2,1,9" in ascending order, to get 1,2,4,5,8,9,13?
Split the string by commas
Parse each substring into an integer
Sort the resulting collection
If you need the result to be a string (it's not clear), convert each integer back into a string and join them together with commas.
If any of those steps causes you difficulties, please be more specific.
Split it into an array of items with String.split().
Convert to an array of numbers with Integer.valueOf().
Sort the array.
Concatenate it all back into a StringBuilder.
As one liner, using Google Collections (updated with Kevin's suggestion)
Joiner.on(",").join(Ordering.natural().onResultOf(new Function<String, Integer>() {
#Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
}).sortedCopy(Arrays.asList("4,2,7,9,1".split(","))));
Split using String.split()
Transform to Integer using a Function (anyone know if there's a constant for this one somewhere?)
Sort using a TreeSet and natural ordering
Join the parts and transform back to a String using Joiner
(old version)
Joiner.on(',').join(
Sets.newTreeSet(
Iterables.transform(
Arrays.asList("13,5,8,4,2,1,9".split(",")),
new Function<String, Integer>() {
#Override
public Integer apply(String from) {
return Integer.parseInt(from);
}}))));
String s = "13,5,8,4,2,1,9";
String[] arr = s.split(",");
Arrays.sort(arr, new Comparator<String>() {
#Override public int compare(String s1, String s2) {
return Integer.parseInt(s1) - Integer.parseInt(s2);
}
});
s = Arrays.toString(arr).replaceAll("[\\[ \\]]", "");
This solution uses:
java.util.Comparator
java.util.Arrays sort and toString
String split and replaceAll
regular expression
I would tokenize the string using StringTokenizer,
parse the values (using Integer.parseInt),
then sort the results using Arrays.sort.
Lastly, re-create the string.
String str = "13,5,8,4,2,1,9";
StringTokenizer tokens = new StringTokenizer(", ");
ArrayList<Integer> ints = new ArrayList<Integer>();
for(String token: tokens)
ints.add(Integer.parseInt(token));
Collection.sort(ints);
String sortedStr = "";
for(int i = 0; i + 1 < ints.size(); ++i)
sortedStr += ints.get(i) + ", ";
if (ints.size() > 0)
sortedStr += ints.lastElement();
Might have some misspellings, but I think not. Also, add the appropriate imports yourself =)
So you have a string containing a comma-delimited set of integers that you need to sort and then output to a string? Try split-ting the string, parse-ing the integers, sort-ing the resulting array, and then join-ing the results together
Java 8+
If you are using Java 8 you can use streams to sort like so :
String str = "13,5,8,4,2,1,9";
String sortedString =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.map(String::valueOf) //convert them back to string
.collect(Collectors.joining(","));//1,2,4,5,8,9,13
If you want an sorted array you can also use :
Integer[] sortedInts =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.toArray(Integer[]::new);//[1, 2, 4, 5, 8, 9, 13]
The idea is the same as Jon Skeet explanation.
An alternative using java.util.Scanner
public class SortString {
public static void main( String [] args ) {
// Read integers using Scanner...
Scanner scanner = new Scanner( "13,5,8,4,2,1,9" ).useDelimiter(",");
// Put them in a Integer list
List<Integer> list = new ArrayList<Integer>();
while( scanner.hasNextInt() ){
list.add( scanner.nextInt() );
}
// And sort it
Collections.sort( list );
System.out.println( list );
}
}
ok you can try this one it work in all case.
package com.java;
import java.util.*;
public class cd
{
public static void main(String s[])
{
Collections col;
List l = sort(s);
System.out.println("\nStrings sorted List ...");
for(int i = 0; i < s.length; i++)
{
System.out.println((String)l.get(i));
}
int ints[] = {
719, 2, -22, 401, 6
};
Integer in[] = new Integer[ints.length];
for(int i = 0; i < in.length; i++)
{
in[i] = new Integer(ints[i]);
}
l = sort(in);
System.out.println("\nIntegers sorted List ...");
for(int i = 0; i < in.length; i++)
{
System.out.println((Integer)l.get(i));
}
}
public static List sort(Object o[])
{
ArrayList al = new ArrayList();
for(int i = 0; i < o.length; i++)
al.add(i, o[i]);
List list = Collections.synchronizedList(al);
Collections.sort(list);
return list;
}
}
This is one way to sorting.
package com.java;
import java.util.ArrayList;
import java.util.Collections;
public class b{
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("9");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");
Collections.sort(arrayList);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in ascending order : ");
for(int i=0; i<arrayList.size(); i++)
System.out.println(arrayList.get(i));
}
}
class SplitStr
{
public static void main(String args[])
{
try
{
String str=args[0]+","+args[1]; //marge two string in one
String sArr[]=str.split(",");
int slen=sArr.length;
int iArr[]=new int[slen];
int temp;
for(int i=0;i<slen;i++)
{
iArr[i]=Integer.parseInt(sArr[i]); //convert String into integer array
}
for(int i=0;i<slen;i++)
{
for(int j=i+1;j<slen;j++)
{
if(iArr[i]>=iArr[j])
{
temp=iArr[i];
iArr[i]=iArr[j];
iArr[j]=temp;
}
}
}
for(int i=0;i<slen;i++)
{
System.out.println(" "+iArr[i]);
}
}
catch(Exception e)
{
System.out.println("input error "+e);
}
}
}
Bash is SO powerful :-)
numbers="1, 2, 9, 4, 7, 5" ; for number in $(echo "$numbers") ; do echo "$number" | tr -d ", "; done | sort | tr "\n" "," ; echo ""

Categories

Resources