I am working with String and String[] in java.
I have one String[] and wanted to convert into String but don't want last index value in it.
String[] arr = new String[]{"1","2","3","4"};
I want new string as 123 only.
Yes, I can iterate arr up to second last index maintain assign the value in the new string. But is there any other way to this thing in the smarter way?
I think about three ways.
First one is using StringBuilder. This takes you full control with minimum garbage. (I would prefer this one)
public static String convert(String... arr) {
// in case of arr is really big, then it's better to first
// calculate required internal buffer size, to exclude array copy
StringBuilder buf = new StringBuilder();
for(int i = 0; i < arr.length - 1; i++)
buf.append(arr[i]);
return buf.toString();
}
Another way is to use Java8 feature String.join():
public static String convert(String... arr) {
return String.join("", arr).substring(0, arr.length - 1);
}
And finally using Stream:
public static String convert(String... arr) {
return Arrays.stream(arr, 0, arr.length - 1).collect(Collectors.joining(""));
}
try this
String[] arr = new String[]{"1","2","3","4"};
String newString = "";
for (int i = 0; i < arr.length -1 ; i++) {
newString += arr[i];
}
System.out.print(newString);
Output
123
Related
I have the following string:
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
And I'm trying to convert it to:
String converted = "aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz";
To be somehow sorted. This is what I have tried so far:
String[] parts = string.split("\\n");
List<String[]> list = new ArrayList<>();
for(String part : parts) {
list.add(part.split(","));
}
for(int i = 0, j = i + 1, k = j + 1; i < list.size(); i++) {
String[] part = list.get(i);
System.out.println(part[i]);
}
So I managed to get first element from each "unit" separately. But how to get all and order them so I get that result?
Can this be even simpler using Java8?
Thanks in advance!
I guess one way to do it would be:
String result = Arrays.stream(string.split("\\n"))
.map(s -> {
String[] tokens = s.split(",");
Arrays.sort(tokens);
return String.join(",", tokens);
})
.collect(Collectors.joining("\\n"));
System.out.println(result); // aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz
Just notice that in case your patterns are more complicated than \n or , - it is a good idea to extract those an separate Pattern(s)
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
String converted = Arrays.stream(string.split("\\n"))
.map(s -> Arrays.stream(s.split(","))
.sorted()
.collect(Collectors.joining(",")))
.collect(Collectors.joining("\\n"));
You can have it the old fashioned way without the use of Java 8 like this:
public static void main(String[] args) {
String s = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
System.out.println(sortPerLine(s));
}
public static String sortPerLine(String lineSeparatedString) {
// first thing is to split the String by the line separator
String[] lines = lineSeparatedString.split("\n");
// create a StringBuilder that builds up the sorted String
StringBuilder sb = new StringBuilder();
// then for every resulting part
for (int i = 0; i < lines.length; i++) {
// split the part by comma and store it in a List<String>
String[] l = lines[i].split(",");
// sort the array
Arrays.sort(l);
// add the sorted values to the result String
for (int j = 0; j < l.length; j++) {
// append the value to the StringBuilder
sb.append(l[j]);
// append commas after every part but the last one
if (j < l.length - 1) {
sb.append(", ");
}
}
// append the line separator for every part but the last
if (i < lines.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
But still, Java 8 should be preferred in my opinion, so stick to one of the other answers.
The Pattern class gives you a possibility to stream directly splitted Strings.
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
Pattern commaPattern = Pattern.compile(",");
String sorted = Pattern.compile("\n").splitAsStream(string)
.map(elem -> commaPattern.splitAsStream(elem).sorted().collect(Collectors.joining(",")))
.collect(Collectors.joining("\n"));
I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.
How do I return a string e.g. H4321 but return the numbers only, not the H. I need to use an array. So far I have:
char [] numbers = new char[5];
return numbers;
Assuming I need a line between those two. String is called value
You can use substring method on String object.
Like this:
String newValue = value.substring(1);
and then call: char[] charArray = newValue.toCharArray();
Another solution - it copies old array without first element. :
char[] newNumbers = Arrays.copyOfRange(numbers, 1, numbers.length);
Use the code bellow:
public String getNumber(){
char [] numbers = new char[5];
numbers = new String("H4321").toCharArray();
String result = "";
for(int i = 0; i < numbers.length ; i++){
if(Character.isDigit(numbers[i])){
result += numbers[i];
}
}
return result;
}
I am trying to convert an arraylist of integers to an string in reverse.
eg (1,2,3,4) converts to "4321".
However I am unable to get my code to work mainly due to the primitive data type error (basically why you give my an arraylist to do an array thing). My code is currently
public String toString() {
int n = arrList.size();
if (n == 0)
return "0";
for (int i = arrList.size(); i > 0; i--);
int nums= arrList[i];
char myChar = (char) (nums+ (int) '0');
String result = myChar.toString(arrList);
return result;
}
Your loop had the wrong range and it didn't do anything, since you terminated it with ;.
In addition, arrList[i] is the way to access an element of an array. To access an element of an ArrayList you use arrList.get(i).
Finally, you should accumulate the characters / digits somewhere before converting them to a String. I suggest a StringBuilder.
StringBuilder sb = new StringBuilder();
for (int i = arrList.size() - 1; i >= 0; i--) {
int num = arrList.get(i);
sb.append(num);
}
String result = sb.toString();
You have many problems. First, you should remove ; after the for loop.
Second, you are not concatenating the result, just saving the last value.
Third, you should loop from the last index, which is arrList.size() - 1.
Fourth, note that the element at place 0 should be counted as well, so you should change your condition to i >= 0. Finally, accessing arraylist's elements should be done using the method get: arrList.get(i).
Now after you understood what your problems are, I would like to suggest a better solution using Java 8:
Collections.reverse(arrList);
String listString = arrList.stream().map(Object::toString)
.collect(Collectors.joining(""));
public String toString() {
int n = arrList.size();
if (n == 0)
return "0";
String str = "" ;
for (int i = arrList.size()-1; i > 0; i--){
int nums= arrList.get(i);
str+= nums ;
}
return str;
}
A ListIterator works too - if you dont want indexing.
ArrayList<Integer> integerList = new ArrayList<Integer>();
StringBuilder sb = new StringBuilder();
ListIterator<Integer> it = integerList.listIterator(integerList.size());
while(it.hasPrevious())
{
sb.append(Integer.toString(it.previous()));
}
String answer = sb.toString();
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());