Java, How to convert a string into an Array - java

I've got a string, for example:
String code = new String("[199, 56, 120]")
My goal is to create and Array that contains only the numbers inside the [] and beetween commas;
In this case it would be for example:
array[0] = 199
array[1] = 56
array[2] = 120
Is possible to do something like this??
Thanks in advance.

You just need to use the split function.
Skip the [ and the ] and you can do something like this:
String input = "199 56 120";
String[] array = input.split(" ");
If you really want [ and the ] then you can use something like
input.replace("[", "");
input.replace("]", "");
To strip the string before you split it.
Edit
It doesn't matter what the format is or what the numbers are or how many they are, you simply edit the split definition according to the format, so if you're case is , then you simply use that as the split parameter.
String input = "[number, number, number]";
String sep = ", ";
String fixedInput = input.replace("[", "").replace("]", "");
String[] array = fixedInput.split(sep);
// array[0] contains first number.
// array[1] contains second number.
If you want an int[] array then you could do something like this:
int[] intArray = new int[array.length];
for(int i = 0; i < array.length; i++)
{
intArray[i] = Integer.parseInt(array[i]);
}

If you want a one-line solution:
String[] array = code.replaceAll("[^\\d ]", "").split(" ");
The in-line call to replaceAll() removes non-digits/spaces.

Related

java string [] array remove special character

how to remove "," in below string specified at s[0,2] location(818001,818002)(151515,151515) and store again to string []
String[] s = {"818001,818002","121212","151515,151515"};
You should explain more detailed your problem.
I think what you want is this:
s = '(818001,818002)(151515,151515)' //the string you have.
s = s.replace(')(',',').replace('(','').replace(')','');// output "818001,818002,151515,151515"
final_string = s.split(','); //output (4) ["818001", "818002", "151515", "151515"]
If you need to remove a comma (or any other char for that matter) in your String array indices the simplest is to iterate through the array and use String.replace():
String[] s = {"818001,818002","121212","151515,151515"};
for(int i=0; i<s.length; i++) {
s[i] = s[i].replace(",", "");
}
System.out.print(Arrays.toString(s)); // [818001818002, 121212, 151515151515]

Given a String how to convert it to an Array: Java

so I'm pretty new at Java and StackOverflow (That's what they all say) and I am stuck at the given problem:
My method is given a String e.g.: "[ 25 , 25 , 125 , 125]". Now the method should return an Array of integers representation of the String provided, that is: it should return
[25,25,125,125].
Here is a segment of my method. Note: input is the String provided
if(input.charAt(index) == '['){
index++;
int start = index;
while(index <= input.length() && input.charAt(index) != ']'){
index++;
}
String[] arrayStr = input.substring(start, index).split(",");
int[] arrayInt = new int[4];
for (int i = 0; i < arrayStr.length; i++){
arrayInt[i] = Integer.parseInt(arrayStr[i]);
}
return arrayInt;
My code works if input is: "[25,25,125,125]" (If there are no spaces between the numbers).
However if there are spaces between the numbers then my code doesn't work and I understand why, but I am struggling to find a way to solve this problem. Any help will be appreciated.
Spaces will fail with Integer.parseInt(arrayStr[i]) (e.g. the string "25 " is not a valid number as it contains a space. (parseInt will throw an exception in such cases.)
However you can solve it quickly by trimming your array elements:
Integer.parseInt(arrayStr[i].trim())
trim() returns a copy of the string without leading/trailing white space
You can replace the space with empty in the string
input=input.replace(" ","")
You can
remove [ and ] and all spaces
split on , to get all tokens
iterate over all tokens
parse string number to int
add parsed int to result array
So your code can look like
String data = "[ 25 , 25 , 125 , 125]";
String[] tokens = data.replaceAll("\\[|\\]|\\s", "").split(",");
int[] array = new int[tokens.length];
for (int i=0; i<tokens.length; i++){
array[i]=Integer.parseInt(tokens[i]);
}
Or if you have Java 8 you can use streams like
int[] array = Stream.of(data.replaceAll("\\[|\\]|\\s", "").split(","))
.mapToInt(number -> Integer.parseInt(number))
.toArray();

Java String to Array

I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5
If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well
For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.
Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5

how to split this string[LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,] as my requirement in java

hello every one i got a string from csv file like this
LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,
how to split this string with comma i want the array like this
s[0]=LECT-3A,s[1]=instr01,s[2]=Instructor 01,s[3]=teacher,s[4]=instr1#learnet.com,s[5]=,s[6]=,s[7]=,s[8]=male,s[9]=phone,s[10]=,s[11]=
can anyone please help me how to split the above string as my array
thank u inadvance
- Use the split() function with , as delimeter to do this.
Eg:
String s = "Hello,this,is,vivek";
String[] arr = s.split(",");
you can use the limit parameter to do this:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example:
String[]
ls_test = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,".split(",",12);
int cont = 0;
for (String ls_pieces : ls_test)
System.out.println("s["+(cont++)+"]"+ls_pieces);
output:
s[0]LECT-3A
s[1]instr01
s[2]Instructor 01
s[3]teacher
s[4]instr1#learnet.com
s[5]
s[6]
s[7]
s[8]male
s[9]phone
s[10]
s[11]
You could try something like so:
String str = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,";
List<String> words = new ArrayList<String>();
int current = 0;
int previous = 0;
while((current = str.indexOf(",", previous)) != -1)
{
words.add(str.substring(previous, current));
previous = current + 1;
}
String[] w = words.toArray(new String[words.size()]);
for(String section : w)
{
System.out.println(section);
}
This yields:
LECT-3A
instr01
Instructor 01
teacher
instr1#learnet.com
male
phone

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

Categories