I have a String of the following kind in Java. The idea is that the string will contain a list of numbers followed by'Y-' or 'N-'. They may be of any length. I need to extract the list of numbers into two, separately.
String str = "Y-1,2,3,4N-5,6,7,8"
//Other examples: "Y-1N-3,6,5" or "Y-1,2,9,18N-36"
I need to break it down into the following arrays:
arr1[] = {1,2,3,4}
arr2[] = {5,6,7,8}
How do I do it?
First split the string into the two arrays string parts
String str = "Y-1,2,3,4N-5,6,7,8";
String str1 = str.substring(2, str.indexOf("N-")); // "1,2,3,4"
String str2 = str.substring(str.indexOf("N-") + 2); // "5,6,7,8"
Then convert the array of strings to an array of ints using the Integer.parseInt(), simple java-8 solution with streams:
int[] array1 = Arrays.stream(str1.split(",")).mapToInt(Integer::parseInt).toArray();
int[] array2 = Arrays.stream(str2.split(",")).mapToInt(Integer::parseInt).toArray();
If you are in a version of java without streams, you need to use a simple for loop instead of the Arrays.stream()
Related
I have a string, ie 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17. How do I get each value and convert it into an array? [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]. I can't find any suggestions about this method. Can help? I did try using regex, but it just simply remove ',' and make the string into one long sentence with indistinguishable value. Is it ideal to get value before and after ',' with regex and put it into []?
You could use following solution
String dummy = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] dummyArr = dummy.split(",");
Try this to convert string to an array of Integer.
String baseString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] baseArray = baseString.split(",");
int[] myArray = new int[baseArray.length];
for(int i = 0; i < baseArray.length; i++) {
myArray[i] = Integer.parseInt(baseArray[i]);
}
Java provides method Split with regex argument to manipulate strings.
Follow this example:
String strNumbers= "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] strNumbersArr= strNumbers.split(",");
You can convert an array of string in array of integer with Streams
int[] numbersArr = Arrays.stream(strNumbersArr).mapToInt(Integer::parseInt).toArray();
Use String.split() and you will get your desired array.
String s1="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] mumbers=s1.split(","); //splits the string based on comma
for(String ss:numbers){
System.out.println(ss);
}
See the working Example
String csv = "Apple, Google, Samsung";
String[] elements = csv.split(",");
List<String> fixedLenghtList = Arrays.asList(elements);
ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);
//ouput
[Apple, Google, Samsung]
if you want an int array
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] split = s.split(",");
int[] result = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
I have a string array in JAVA like:
String[] fruits = {"banana", "apple", "orange"};
How can I access to a character/substring of a string member? For example I want to show the second character of first member "banana" which is 'a' and change it to 'b'. Should I make a new string equal to my array member, do the manipulation and assign the new string to my array list like this:
string manipulate = fruits[0];
//do manipulation on 'manipulate' then:
fruits[0] = manipulate;
or there is a builtin or better way?
Thanks
Java's Strings are immutable, meaning you can't change them. Instead, as #AshishSingh notes in the comments, you'll need to create a new String.
Just do this:
fruits[0] = manipulate(fruits[0]);
Here, manipulate() is your function which takes an input string, manipulates it however you want, and then returns the manipulated string.
public String manipulate(String oldStr) {
StringBuilder newStr = new StringBuilder(oldStr);
newStr.setChar(1, 'b')
return newStr.toString();
}
I'm using StringBuilder which is a mutable object, so can have elements reassigned. I set the second character to 'b' and then return the new String.
The Java String object is immutable, so you can't modify its internal value.
char charArray[] = fruits[index].toCharArray();
charArray[2] = 'b';
After modifying the elements in the character array, put it back into fruits array.
fruits[index] = String.valueOf(charArray);
The existing fruits[index] will be replaced by the new String.
If you want to access a particular character of a String, use, String.charAt(index).
That said, you cannot change a character in a String because Strings are immutable in Java.
If you want to change a character in a given String, you will actually have to create a new String.
Example :
String[] fruits = {"banana", "apple", "orange"};
String banana = fruits[0];
char[] chars = banana.toCharArray();
chars[0] = 'c';
chars[4] = 'd';
String newStr = String.valueOf(chars);
System.out.println(newStr);
Output :
canada
This is how you can do it.
int indexOfArray=1;
int indexOfString=1;
char charToChange='x';
String fruits[] = {"banana", "apple", "orange"};
StringBuilder manipulate = new StringBuilder(fruits[indexOfArray]);
manipulate.setCharAt(indexOfString, charToChange);
fruits[indexOfArray]=manipulate.toString();
How can I convert int[] to comma-separated String in Java?
int[] intArray = {234, 808, 342};
Result I want:
"234, 808, 342"
Here are very similar reference question but none of those solution provide a result, exact I need.
How to convert an int array to String with toString method in Java
How do I print my Java object without getting "SomeType#2f92e0f4"?
How to convert a List<String> into a comma separated string without iterating List explicitly
What I've tried so far,
String commaSeparatedUserIds = Arrays.toString(intArray); // result: "[234, 808, 342]"
String commaSeparatedUserIds = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", ""); // result: "234808342"
String commaSeparatedUserIds = intArray.toString(); // garbage result
Here's a stream version which is functionally equivalent to khelwood's, yet uses different methods.
They both create an IntStream, map each int to a String and join those with commas.
They should be pretty identical in performance too, although technically I'm calling Integer.toString(int) directly whereas he's calling String.valueOf(int) which delegates to it. On the other hand I'm calling IntStream.of() which delegates to Arrays.stream(int[]), so it's a tie.
String result = IntStream.of(intArray)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
This should do
String arrAsStr = Arrays.toString(intArray).replaceAll("\\[|\\]", "");
After Arrays toString, replacing the [] gives you the desired output.
int[] intArray = {234, 808, 342, 564};
String s = Arrays.toString(intArray);
s = s.substring(1,s.length()-1);
This should work. basic idea is to get sub string from Arrays.toString() excluding first and last character
If want quotation in result, replace last line with:
s = "\"" + s.substring(1,s.length()-1) + "\"";
You want to convert the ints to strings, and join them with commas. You can do this with streams.
int[] intArray = {234, 808, 342};
String s = Arrays.stream(intArray)
.mapToObj(String::valueOf) // convert each int to a string
.collect(Collectors.joining(", ")); // join them with ", "
Result:
"234, 808, 342"
This is the pattern I always use for separator-joining. It's a pain to write this boilerplate every time, but it's much more efficient (in terms of both memory and processing time) than the newfangled Stream solutions that others have posted.
public static String toString(int[] arr) {
StringBuilder buf = new StringBuilder();
for (int i = 0, n = arr.length; i < n; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(arr[i]);
}
return buf.toString();
}
I have a line from a dataset like this : vhigh,vhigh,2,2,small,low,unacc`
and I am trying to read the first 6 strings
vhigh,vhigh,2,2,small,low
to a String array and the last String
unacc
to another String variable.
I tried to use String[] arr = line.split(",") and then doString var = arr[5] but this also stored the last string to the array.
Does anyone has another idea ?
You can use String.split() to split input into an array, Arrays.copyOfRange() to copy first elements into new array, and String.join() to join those parts to a new String.
String input = "vhigh,vhigh,2,2,small,low,unacc";
String[] inputParts = input.split(",");
String firstSix = String.join(",", Arrays.copyOfRange(inputParts, 0, 6));
String last = inputParts[6];
System.out.println(firstSix);
System.out.println(last);
e.g.:
If the number is 234, I would like the result to be List<String> containing 2,3,4 (3 elements)
If the number is 8763, I would like the result to be List<String> containing 8,7,6,3 (4 elements)
Does commons-math already have such a function?
Convert the number to a String (123 becomes "123"). Use Integer.toString.
Convert the string to a char array ("123" becomes {'1', '2', '3'}). Use String.toCharArray.
Construct a new, empty Vector<String> (or some other List type).
Convert each char in the char array to a String and push it onto the Vector ({'1', '2', '3'} becomes a Vector with "1", "2" and "3"). Use a for loop, Character.toString and List.add.
Edit: You can't use the Vector constructor; have to do it manually.
int num = 123;
char[] chars = Integer.toString(num).toCharArray();
List<String> parts = new Vector<String>();
for (char c : chars)
{
parts.add(Character.toString(c));
}
There isn't an easier way to do this because it really isn't a very obvious or common thing to want to do. For one thing, why do you need a List of Strings? Can you just have a list of Characters? That would eliminate step 3. Secondly, does it have to be a List or can it just be an array? That would eliminate step 4.
You can use the built in java.util.Arrays.asList:
int num = 234;
List<String> parts = Arrays.asList(String.valueOf(num).split("\\B"));
Step by step this:
Converts num to a String using String.valueOf(num)
Splits the String by non-word boundaries, in this case, every letter boundary except the start and the finish, using .split("\\B") (this returns a String[])
Converts the String[] to a List<String> using Arrays.asList(T...)
Arrays.asList( String.valueOf(number).toCharArray() )
Try this:
Arrays.asList(String.valueOf(1234).split("(?!^)"))
It will create list of Strings:
["1", "2", "3", "4"]
This seems like homework.
Consider using % and / to get each digit instead of converting the entire number to a String