I have a string s="1,2,3,4,5" . I am using the split() method to split the string then i want to store it into an array of ints.
I tried doing the following but it doesn't work.
int i[]=Integer.parseInt(s.split(","));
I want to know if it is possible to do this without using a loop.
There is something like Array.convertAll in C# but I don't know of a similar thing in java.
In java there is no such way (method) by which you can directly get a int array by passing String array
So u must write some method to do this...
and if there is condition that you must not have to use loop then ...i write a code by adding some more code in Adel Boutros may u get help from this but its better to you loop.. :)
public class Test {
public static void main(String[] args) {
String s = "1,2,3,4,5";
int size = 0;
int[] arr = new int[s.split(",").length];
findInt(s, arr, size);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
static void findInt(String s, int[] arr, int index) {
String aa = null;
if (s == null) {
return;
}
if (s.length() != 1) {
String text = s.substring(0, s.indexOf(","));
arr[index] = Integer.parseInt(text);
} else {
arr[index] = Integer.parseInt(s);
}
if (s.length() != 1) {
aa = s.substring(s.indexOf(",") + 1, s.length());
}
findInt(aa, arr, ++index);
}
}
If you don't want to use a loop, you can call a method which does the loop for you.
e.g. (You will need to write the convertToInts method)
int[] ints = convertToInts(s);
In pure Java, there is no way of doing this.
In Apache Commons (especially Commons Lang), there are transform utilities that only take a function with array and do what you want, you don't have to code the loop by yourself.
public static void main (String []args) {
String s="1,2,3,4,5";
int size = 0;
int [] arr = new int [s.length];
findInt(s, arr, size);
}
void findInt(String s, int [] arr, int index) {
if (s.isEmpty()) {
return;
}
String text = s.substring(0,s.indexOf(","));
arr[index] = Integer.parseInt(text);
findInt(text.substring(1), arr, ++index);
}
PS: My method uses the recursive approach. The variable size will be the actual size of the int array.
This one will probably fail your contest, but it indeed avoids the loop :)
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
String s = "1,2,3,4,5";
String s1 = s.replaceAll("(\\d+),?", "arr[i++]=$1;");
int[] arr = new int[s.split(",").length];
jsEngine.put("arr", arr);
jsEngine.eval("var i=0;" + s1);
}
The result is an int[] filled with numbers from your String.
Related
I'm having trouble with this problem.
Here is the code I wrote out:
package com.jdewey.rvrs;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your string: ");
String userIn = console.nextLine();
int inLength = userIn.length();
stringRvrs(userIn, inLength);
}
public static void stringRvrs(String x, int length){
for(int i = 1; i <= length; i++){
int y = -1 * i + length;
System.out.print(x.substring(y));;
}
}
}
It's supposed to output "tset" if you were to input "test"
Please help!
It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:
public static void stringRvrs(String x, int length){
String result = "";
for(int i = length - 1; i >= 0; i--){
result = result + x.charAt(i);
}
System.out.println(result);
}
Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.
Try StringBuilder as in:
public static void stringRvrs(String x){
char [] all = x.toCharArray();
StringBuilder concate = new StringBuilder();
for(int i = all.length-1;i >= 0;i--){
concate = concate.append(String.valueOf(all[i]));
}
System.out.println(x+" reversed to "+concate);
}
No need to pass int length as an parameter to the method.
you can simply use stringBuilder.reverse();
your method should look like this after the changes,
public static void stringRvrs(String x, int length){
StringBuilder sb = new StringBuilder(x);
System.out.println(sb.reverse());
}
There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.
I'm currently doing an activity that requires me to write this:
Write a definition for a static method stringHeads that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
My code is currently something like this:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p)
e = b - 1
for (int de = 0; rad.length > de; de++)
rad[de] = s.substring(0,e);
for (String str : rad)
return str;
}
//Just ignore the rest
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon"
stringHeads(a,b)
The output should be "Rado" , "Ra", "Rad", "Ra", "".
The error that I'm currently getting is that String cannot be converted to String[].
Basically my question is how to fix this error and if a better code can be written.
Three things:
e would be constant if you enter the second loop.
e could be larger than s.length() - you didn't handle this case.
You return a String instead of a String[]
And please always use braces if you use loops, even if the loop only contains one statement. It is much more readable and can avoid errors.
I think you will have to rethink your whole function. Don't know if it would be helpful to write the function for you.
Hints:
Write only one loop!
String[] rad = new String[p.length];
for (int i=0; i < p.length; i++) {
if (s.length() < ??) {
rad[i] = s.substring(0,??);
} else {
??
}
}
return rad;
I hope this will help you to get the answer yourself.
See my code below hope it helps:-
I provided the comments instead of explaining it in paragraph.
As for your error, you are returning String from method but expected is an array of String.
public static void main(String[] args){
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] output=stringHeads(a,b);
for(String s:output){
System.out.println(s);
}
}
Your method can be like below:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
//Iterate over integer array
for(int index=0; index<p.length; index++){
//Extracting the integer value from array one by one
e=p[index];
//If integer value is greater than String length
if(e>s.length()){
//Put the entire String in String array
rad[index]=s;
}else{
//Put the Substring value with range 0 to e i.e. integer value
rad[index]=s.substring(0,e);
}
}
return rad;
}
You could simplify you code by just using a single iteration with an alternative variable.
public static void main (String[] args) throws java.lang.Exception
{
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] result = stringHeads(a,b);
for(String x : result) System.out.println(x);
//Or you can write a separate display method instead.
}
public static String[] stringHeads(int[] p, String s)
{
String[] rad = new String[p.length];
//Use this variable for array allocation/iteration.
int i=0;
//Simply iterate using this for-each loop.
// This takes care of array allocation/ substring creation.
for (int x : p)
rad[i++] = s.substring(0,x);
return rad;
}
Please check the code below
public static String[] stringHeads(int[] intArray, String str) {
String[] result = new String[intArray.length];
int count=0;
for (int intValue : intArray)
{
result[count] = str.substring(0,intValue);
count++;
}
return result;
} //Just ignore the rest
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] strArray=stringHeads(a,b);
int count=0;
for(String str:strArray)
System.out.println(++count+"" +str);
}
Change your method like this
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
rad[e] = s.substring(0, b);
e++;
}
return rad;
}
For use this method
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0};
String b = "Radon";
String[] stringHeads = stringHeads(a, b);
for (String stringHead : stringHeads) {
System.out.println(stringHead);
}
}
Output is
Rado
Ra
Rad
Ra
There is no need for the for loop that iterates through the integer array p
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
for (int de = 0; de < p.length; de++){
if (p[de] < s.length())
rad[de] = s.substring(0,p[de]);
else
rad[de]=s;
}
return rad;
}
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
if(b<=s.length()){
rad[e] = s.substring(0, b);
}
e++;
}
return rad;
}
Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}
I'm trying to remove duplicates from the array, but it is not working.
Am I missing something ?
Code :-
class RemoveStringDuplicates {
public static char[] removeDups(char[] str) {
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
str[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return str;
}
public static void main(String[] args) {
char str[] = "test string".toCharArray();
System.out.println(removeDups(str));
}
}
Output :-
tes ringing //ing should not have been repeated!
Instead of assigning the characters into the same array, you should use a new array. Because, after removing the duplicates, the trailing elements are not being removed, and thus are printed.
So, if you use a new array, the trailing elements would be null characters.
So, just create an new array:
char[] unique = new char[str.length];
And then change the assignment:
str[res_ind] = str[ip_ind];
to:
unique[res_ind] = str[ip_ind];
Also, you can consider using an ArrayList instead of an array. That way you won't have to maintain a boolean array for each character, which is quite too much. You are loosing some not-needed extra space. With an ArrayList, you can use the contains method to check for the characters already added.
Well, you can also avoid doing all those counting stuffs manually, by using a Set, which automatically removes duplicates for you. But most implementation does not maintain insertion order. For that you can use LinkedHashSet.
The specific problem has already found a solution, but if you are not restricited to using your own method and can use the java libraries, I would suggest something like this:
public class RemoveDuplicates {
// Note must wrap primitives for generics
// Generic array creation not supported by java, gotta return a list
public static <T> List<T> removeDuplicatesFromArray(T[] array) {
Set<T> set = new LinkedHashSet<>(Arrays.asList(array));
return new ArrayList<>(set);
}
public static void main(String[] args) {
String s = "Helloo I am a string with duplicates";
Character[] c = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
c[i] = s.charAt(i);
}
List<Character> noDuplicates = removeDuplicatesFromArray(c);
Character[] noDuplicatesArray = new Character[noDuplicates.size()];
noDuplicates.toArray(noDuplicatesArray);
System.out.println("List:");
System.out.println(noDuplicates);
System.out.println("\nArray:");
System.out.println(Arrays.toString(noDuplicatesArray));
}
}
Out:
List:
[H, e, l, o, , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]
Array:
[H, e, l, o, , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]
The linkedhashset retains ordering, which might be especially important for things like characterarrays.
Try This:
public static char[] removeDups(char[] str) {
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
char a[] = new char[str.length];
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
a[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return a;
}
You basically are updating the str variable in the loop. Updating it and again looping on the updated array.
I believe the problem is caused by the fact that you are iterating over str while you are modifying it (by the line str[res_ind] = str[ip_ind]). If you copy the result to another array, it works:
class RemoveStringDuplicates {
public static char[] removeDups(char[] str) {
char result[] = new char[str.length];
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
result[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return result;
}
public static void main(String[] args) {
char str[] = "test string".toCharArray();
System.out.println(removeDups(str));
}
}
All the other answers seem to be correct. The "ing" that you see at the end of the result is actually untouched characters already in the array.
As an alternative solution (if you want to conserve memory), you can loop over the last part of the array to delete the characters at the end because you already know they are duplicate.
//C# code, I think you just need to change str.Length here to str.length
for (int delChars = res_ind; delChars < str.Length; delChars++)
{
str[delChars] = '\0';
}
You are totally abusing the Java language with your code. The data structure classes in the standard libraries are the main point of using Java. Use them.
The correct way to code something to do what you want is here:
class RemoveStringDuplicates {
public static String removeDups(CharSequence str) {
StringBuilder b = new StringBuilder(str);
HashSet<Character> s = new HashSet<Character>();
for(int idx = 0; idx < b.size(); idx++)
if(mySet.contains(b.charAt(idx)))
b.deleteCharAt(idx--);
else
s.add(ch);
return b.toString();
}
public static void main(String[] args) {
System.out.println(removeDups(str));
}
}
There are probably even better ways of doing it, too. Don't go avoiding Java's data structures.
If you are writing code that is performance-sensitive enough that you have to use primitive code like that in your question, you should be using a different language, like C.
I have a string that I want to split with a certain delimiter
private int [] mMaxValues;
public void setMaximum(String maximum) {
mMaxValues = splitByDelimiter(maximum, ":");
}
But the splitByDelimiter method return a string array into an int array
public String[] splitByDelimiter(String list,String delimiter) {
String[] items = list.split("\\" + delimiter);
for (String s : items) {
s.trim();
}
return items;
}
What is the best way to fix this problem? I'm guessing that iterating the string array and casting them to integers isn't the best solution.
I could also create a new splitByDelimiter that returns an int array but I'm guessing there is a better solution than that..
Is this a situation where you could use generics (I don't have a lot of experience with generics)?
Thx :)
You need to convert string array to int array explicitly. Use:
public void setMaximum(String maximum) {
Strin[] array = splitByDelimiter(maximum, ":");
int i = 0;
mMaxValues = new int[array.length];
for (String value : array) {
mMaxValues[i] = Integer.parseInt(value);
i++;
}
}
Also you need to handle few cases which may cause NullPointerException :
maximum is null
array is null
NumberFormatException may be raised while parsing Integer.parseInt(value), handle it.
Loop over the string array and store them in an int array.
String input = ...;
String[] parts = input.split(':');
int[] result = new int[parts.length];
for (int n = 0; n < parts.length; ++n)
{
result[n] = Integer.parseInt(parts[n]);
}
return result