I have a number that is submitted by the user.
I want to make something like this: 1568301
to an array like this: 1, 5, 6, 8, 3, 0, 1.
How can I do this without adding "," between every digit or something like that? (type int).
Thanks.
String str = "123456";
str.toCharArray();
will do roughly what you want. A more complex version using a regular expression is:
String str = "123456";
str.split("(?<!^)");
which uses a negative lookbehind (split() takes a regexp - the above says split on anything provided the element to the left isn't the start-of-line. split("") would give you a leading blank string).
The second solution is more complex but gives you an array of Strings. Note also that it'll give you a one-element empty array for a blank input. The first solution gives you an array of Chars. Either way you'll have to map these to Integers (perhaps using Integer.parseInt() or Character.digit()?)
"1568301".toCharArray() should do the job.
You can use the Split with ""
It'll be like this:
String test = "123456";
String test2[] = test.split("");
for (int i = 1; i < test2.length; i++) {
System.out.println(test2[i]);
}
If your number is in String format, you can simply do this:
String str = "1568301";
char[] digitChars = str.toCharArray();
Are expecting something like this
String ss ="1568301";
char[] chars = ss.toCharArray();
cant you simply populate the array by iterating over the String ??
char[] arr = new char[str.length];
for(int i=0; i<str.length; i++){
arr[i] = str.charAt(i);
}
or even better
char[] arr = "0123456".toCharArray();
To get the values in an array of integers:
String str = "1568301";
int[] vals = new int[str.length];
for (int i = 0; i < str.length(); i++) {
vals[i] = Character.digit(str.charAt(i), /* base */ 10));
}
The second parameter of Character.digit(char, int) is the number base. I'm assuming your number is base 10.
I guess you are looking at to have an array of int.
I would suggest to have the following code :
String str = "1568301";
int [] arr = new int[str.length()];
for(int i=0; i<arr.length; i++)
{
arr[i] = str.charAt(i)-'0';
}
Related
Convert aaabbcc string to a string a3b2c2.Here is there any way to store integer value 3 in a character array.Can I convert aaabbcc string into a string a3b2c2.
Integer data type requires 32 bit or 4 bytes space whereas character array contains blocks of 16 bits or 2 bytes space.
You might want to create an another integer array to hold your count values as this is not possible in the same character array directly.
There is a workaround of storing ASCII values of corresponding count values as characters in the same array but it might lead to ambiguity if there are numbers present as part of your original character array.
Hence I would suggest you use a separate integer array.
String str = "aaabbcc";
char c;
ArrayList<String>count=new ArrayList();
for(int i = 0; i < str.length(); i++){
if(!count.contains(str.charAt(i)+"")){
count.add(str.charAt(i)+"");
}
}
int [] dd = new int [count.size()];
for (int i = 0; i < str.length(); i++) {
c=str.charAt(i);
for(int j=0;j<count.size();j++){
if(count.get(j).equals(c+"")){
dd[j]++;
}
}
}
String newS="";
for(int i=0;i<count.size();i++){
newS+=count.get(i)+dd[i];
}
str = newS;
System.out.println(str);
you can do it using String, like you want to store 3 at 2nd position so do like this-
int n = 3;
String s = Integer.toString(n);
ch[1] = s.charAt(0); // ch[1] is representing 2nd position in aaabbc
String contains an unknown length of numbers which are seperated by "-", for example:
string = "4-12-103-250-302"
I need these numbers in an integer array like this:
intArray[] = { 4, 12, 103, 250, 302 }
Can you give me a code example/solution?
You can use the String.Split method in Java.
Then convert the Array to an Integer Array.
string str = "4-12-103-250-302";
String[] parts = string.split("-");
int[] intArray = new int[parts.length];
for(int i = 0; i < parts.length -1; i++)
{
intArray[i] = Integer.parseInt(parts[i]);
}
Then you can just access all of the parts just as an array would work.
intArray[0]
intArray[1]
.
.
etc
You want to split the string into an array by a character delimiter. Then you want to apply a function to each item in the array to make it into an integer.
In php:
<?php
$string = "4-12-103-250-302";
$aray = $string.split("-");
array_walk($aray, 'intval');
Other languages will have similar constructs.
Since Java < 8 doesn't have use lambdas, try this:
str = "4-12-103-250-302";
String[] straray = str.split("\\-", -1);
int[] intArray = new int[straray.length];
for (int i=0; i < straray.length; i++) {
intArray[i] = Integer.parseInt(straray[i]);
}
public static void main(String[] args) {
String brandmodel="VolkswagenGolf";
String [] splitedstring=new String[13]
//how to insert every 3 letters in splitedstring array
}
What i want is to split the above string in every 3 letters.
For example
i want to save from the above string the next
Vol,ksw,age,nGo,lf
i have read here some crazy codes but i did not understand them,i want the simplest way.
I have not learned Regex yet
Calculate the number of parts you will have and create an array:
int parts = (string.length() + 2) / 3;
String splitted[] = new String[parts];
Fill the array, using String.substring(int, int):
for (int i = 0; i < parts; ++i)
{
int x = i * 3;
splitted[i] = string.substring(x, Math.min(string.length(), x + 3));
}
Substring takes a string out of another string, using indices.
The problem is that if you take a range that goes out of the string, an exception will be thrown. So what I do, is limiting the endIndex to the string length, by using Math.min(int, int). It will always return the smallest of the two passed values.
Example of this going wrong, without Math.min():
String str = "test";
String substr = str.substring(2, 9);
This fails (Exception) because, 9 is out of the range of str. str is only 4 characters long. So, valid startIndices are: {0, 1, 2, 3} and valid endIndices are in this case: {0, 1, 2, 3, 4}.
You could use regex look-behind matching the last match plus any 3 characters:
String[] splitString = brandmodel.split("(?<=\\G...)");
The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))
Output:
[Vol, ksw, age, nGo, lf]
There's no "crazy code" required, it's a relatively straightforward:
String[] res = new String[(s.length()+2)/3];
for (int i = 0 ; i != res.length ; i++) {
res[i] = s.substring(3*i, Math.min(3*i+3, s.length()));
}
On ideone: link.
It works for all length of String
String brandmodel="VolkswagenGolf";
List <String> splitedstring = new ArrayList<String>();
int i = 0;
while(brandmodel.length() > 2 )
{
splitedstring.add(brandmodel.substring(0,3));
brandmodel = brandmodel.substring(3);
}
if(brandmodel.length() > 0)
splitedstring.add(brandmodel);
I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!
Suppose I have a string of 123456789. I would like to split this string and each number goes in a different slot in the array. I can't use the split() method because there is nothing to split on. How would I accomplish this in Java.
int x=123456789;
char[] array = x.toString().toCharArray();
int intarray[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
intarray[i] = Integer.parseInt(array[i]);
}
And after this you intarray will be array of your numbers.
If your integer can be negative too, you must take it's absolute value and make same operations, and after that multiple first array value by -1. But I guess, it's not needed.
EDIT:
I think, I don't understand your question properly. If you want to split only string, you must use this lines only. I wrote about integers,which might be helpful too.
string x="123456789";
char[] array = x.toCharArray();
If you're only dealing with non-negative integers, the toCharArray() method should be suitable for you. It gives you the string as an array.
The String class has a neat method for doing this, toCharArray().
You can use the following to avoid creating Strings.
long x = x;
ByteBuffer bb = ByteBuffer.allocate(18);
if (x == 0) {
bb.put((byte) 0);
} else {
while (x > 0) {
bb.put((byte) (x % 10));
x /= 10;
}
}
int len = bb.position();
byte[] digits = new byte[len];
for (int i = 0; i < len; i++)
digits[i] = bb.get(len - i - 1);
is it compelsory that the data will be of single digit ?If the data may come in multiple digits then it will not be possible to identify whether the numeric value is of single digit of multiple digit ?
e.g. if it is 12(twelve) then if all string is 512 then how will you identify whether to represent 512 as 5,1,2 or 5,12 ?
if it is fix that the numbers will be in single digits and non negetives then toCharArray() of String class will work for you