Convert String to int[] array - java

how could I convert my String to int array?
my input:
String numbers = "123456";
What I'd like to reach:
Int numbers[]={1,2,3,4,5,6};
That String was splitted from String with this number.

If the above question is for Java.
String numbers = "123456";
int[] array = new int[numbers.length()];
for (int i = 0; i < numbers.length(); i++) {
array[i] = Character.getNumericValue(numbers.charAt(i));
System.out.println("\n"+array[i]);
}

Java 8 one liner would be:
int[] integers = Stream.of( numbers.split("") )
.mapToInt(Integer::valueOf)
.toArray();

I don't know what language you are working with. But I can tell you in c++.
character codes of digits start from 48(dec). You can add and remove this value for each element.
The code could roughly look like this.
int * _numbers=new int[numbers.size()];
for(int i=0;i<numbers.size();i++)
_numbers[i]=numbers[i]+48;

The most straightforward way is to create an array variable and loop through the string characters and push them into the array.
var str = "123456";
var arr = [];
for (let n of str) {
arr.push(parseInt(n))
}
console.log(arr);

Related

Get Integer and Character in Same Line

This is my raw code
int n1=nextInt();
String ch=next().split("");
int n2=nextInt().split("");
if i want to get input line 5A11 (in same line).What should i do to get input like this.IS it possible to get input like this in java
Read the input as a String. Then use below code to remove the characters from the String followed by summing the integers.
String str = "123ABC4";
int sum = str.replaceAll("[\\D]", "")
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(sum);
You can use String#split.
int[] parseInput(String input) {
final String[] tokens = input.split("A"); // split the string on letter A
final int[] numbers = new int[tokens.length]; // create a new array to store the numbers
for (int i = 0; i < tokens.length; i++) { // iterate over the index of the tokens
numbers[i] = Integer.parseInt(tokens[i]); // set each element to the parsed integer
}
return numbers;
}
Now you can use it as
int[] numbers;
numbers = parseInput("5A11");
System.out.println(Arrays.toString(numbers)); // output: [5, 11]
numbers = parseInput("123A456");
System.out.println(Arrays.toString(numbers)); // output: [123, 456]
String input = "123C567";
String[] tokens = input.split("[A-Z]");
int first = Integer.parseInt(tokens[0]);
int second = Integer.parseInt(tokens[1]);

How to return a string without the first character using an array

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;
}

String to Array (Java)

So my issue here is that I am trying to take in a String from user input, but then I need to convert that string into an array.
So as an example, the user inputted string would be "Hello", and the array (named arr) would be: arr[0]="H" arr[1] = "e" and so on. If anyone can point me in the right direction I would appreciate it a lot!
Use the standard library method:
char[] arr = str.toCharArray();
Documentation: java.lang.String.toCharArray()
There's a built in function to convert a string to a character array:
String myString = ...;
char[] chars = myString.toCharArray();
If you need each character as a stirng, you can loop over the character array and convert it:
String myString = ...;
String[] result = new String[myString.length];
char[] chars = myString.toCharArray();
for (int i = 0; i < chars.length; ++i) {
result[i] = String.valueOf(chars[i]);
}
Read javadoc:
String - toCharArray method
public char[] toCharArray()
Converts this string to a new character array.
String hello = "Hello";
String[] array = hello.split("");
You can use String.split("") like
String[] arr = str.split("");
That will give you an array arr where each substring is one character
[H, e, l, l, o]
Another option might be String.toCharArray() if a char[] is acceptable like
char[] arr = str.toCharArray();

Sort comma separated numbers in a single String Array In Java

I have one String array:
String[] digits = {"2,5,1,6"};
I want to sort this string array, without using a temp variable in Java.
Like this 1,2,5,6
String [] digits = string.split(",");
Arrays.sort( digits );
System.out.println(Arrays.toString(digits));
Since Java 8 you can write something like
String[] digits = { "2,11,5,1,6" };
digits[0] = Stream.of(digits[0].split(","))
.mapToInt(Integer::parseInt)//convert value to int
.sorted()//sort integer values
.mapToObj(String::valueOf)//convert values back to String
.collect(Collectors.joining(","));//join values using "," delimiter
System.out.println(digits[0]);
Output: 1,2,5,6,11
first you need to convert the items inside the digits array into integers
int [] forSorting = new int [digits.lenght];
for(int x = 0; x < digits.length; x++){
forSorting [x] = Integer.parseInt(digits [x]);
}
//sort forSorting here
You can use it like this:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
Collections.sort(list);

Flip a Hex String

Acording to a other question made here Split a Hex String without spaces and flip it, I write this new question more clearly here.
I have an Hex String like this:
Hex_string = 2B00FFEC
What I need is to change the order of the Hex String to start from the latest characters, so this would be like this:
Fliped_hex_string = ECFF002B
In the other question I asked a way to achieve this using the .split() method. But there should be another way to get this in a better way.
As simple as you can is
String s = "2B00FFEC";
StringBuilder result = new StringBuilder();
for (int i = 0; i <=s.length()-2; i=i+2) {
result.append(new StringBuilder(s.substring(i,i+2)).reverse());
}
System.out.println(result.reverse().toString()); //op :ECFF002B
OP constrains the character length to exactly 8 characters in comments.
A purely numeric answer (inspired from idioms to convert endianness); saves going to and from strings
n is an int:
int m = ((n>>24)&0xff) | // byte 3 to byte 0
((n<<8)&0xff0000) | // byte 1 to byte 2
((n>>8)&0xff00) | // byte 2 to byte 1
((n<<24)&0xff000000); // byte 0 to byte 3
If you need to convert this to hexadecimal, use
String s = Integer.toHexString(m);
and if you need to set n from hexadecimal, use
int n = (int)Long.parseLong(hex_string, 16);
where hex_string is your initial string. You need to go via the Long parser to allow for negatives.
You could do something like:
String a = "456789AB";
char[] ca = a.toCharArray();
StringBuilder sb = new StringBuilder(a.length());
for (int i = 0; i<a.length();i+=2)
{
sb.insert(0, ca, i, 2);
}
This also extends to longer Strings if needed
Perhaps you should try something as simple as this:
public static String flip(final String hex){
final StringBuilder builder = new StringBuilder(hex.length());
for(int i = hex.length(); i > 1; i-=2)
builder.append(hex.substring(i-2, i));
return builder.toString();
}
public static void main(String args[]){
System.out.println(flip("2B00FFEC"));
}
The output is: ECFF002B
Next time you ask a question, perhaps you should show us some code you've written used in order to solve your problem (and then ask us why your code doesn't work, not your problem). You will not learn anything from us just providing answers without you knowing how they work.
This method seems to do what you want
String changeHexOrder(String s) {
char[] arr = s.toCharArray();
char tmp;
//change positions of [i, i + 1 , , , , , ,length - i - 2, length - i - 1]
for (int i = 0; i < arr.length / 2; i += 2) {
tmp = arr[i];
arr[i] = arr[arr.length-i-2];
arr[arr.length-i-2] = tmp;
tmp = arr[i+1];
arr[i+1] = arr[arr.length-i-1];
arr[arr.length-i-1] = tmp;
}
return new String(arr);
}
This worked for me
StringBuilder lsbToMsb=new StringBuilder();
for(int i=input.length();i>0;i-=2)
{
lsbMsb.append(lsbToMsb.substring(i-2,i));
}
String lsbMsb=lsbMsb.toString();

Categories