I want the following string to be stored into an array but it throws ArrayOutOfBound Exception.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] arr = {};
String str = "Hello My Name is Ivkaran";
for (int i = 0;i < str.length(); i++){
System.out.println(str.charAt(i));
arr[i] = str.charAt(i);
}
}
You've declared an array of length 0 with this line:
char[] arr = {};
To assign anything to that array, it must be initialized to some non-zero size. Here, it looks like you need it to be the same size as the string.
String str = "Hello My Name is Ivkaran";
char[] arr = new char[str.length()];
You can also just call toCharArray() on the String to get a char[] with the contents copied into it already.
char[] arr = str.toCharArray();
Arrays are not dynamic in Java. Either use an arraylist or create the array with a dimention as:
char[] arr = new char[str.length()]
Also move this line below the
String str = "Hello My Name is Ivkaran";
Then continue as originally.
Just do this:
String str = "Hello My Name is Ivkaran";
char[] arr = str.toCharArray();
Related
I am trying to write my own string reverse algorithm (I know this already exists in java but I am doing this for education). The code below is what I have so far. It outputs only half the string reversed. I have done some debugging and the reason is that it is changing stringChars2 at the same time as stringChars but I have no idea why that is happening as I am only trying to change stringChars. All help greatly appreciated.
EDIT my question was not "how to reverse a string" which has been asked before... but why my objects where changing without instruction, the answer below completely explains the problem.
public static void main(String[] args) {
//declare variables
Scanner input = new Scanner(System.in);
String myString = "";
int length = 0, index = 0, index2 = 0;
//get input string
System.out.print("Enter the string you want to reverse: ");
myString = input.next();
//find length of string
length = myString.length()-1;
index2 = length;
//convert to array
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
//loop through and reverse order
while (index<length) {
stringChars[index] = stringChars2[index2];
index++;
index2--;
}
//convert back to string
String newString = new String(stringChars);
//output result
System.out.println(newString);
//close resources
input.close();
}
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
On the second line you are assigning stringChars2 to the same object as stringChars so basically they are one and the same and when you change the first you are changing the second as well.
Try something like this instead:
char[] stringChars = myString.toCharArray();
char[] stringChars2 = myString.toCharArray();
You can read more about it here
All that is not necessary.
You can simply reverse a string with a for loop (in a method):
public String reverseString(String str)
{
String output = "";
int len = str.length();
for(int k = 1; k <= str.length(); k++, len--)
{
output += str.substring(len-1,len);
}
return output;
}
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();
I have something like the below:
char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();
I get error "incompatible types, char[] cannot be converted to char". My final product I'd like something like the below:
array = {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}};
array becomes a [2][5] array in the end result. Is toCharArray() the incorrect method to use?
You need to have a double array. Something like
char[][] arr = new char[2][];
arr[0] = a.toCharArray();
You need an array of arrays. Something like this:
char[][] array = new char[5][];
You have to use toCharArray to get a char[] back; the problem is where you put it after you extract it.
Change your array variable to be a char[][], and define it as such:
char[][] array = new char[2][5];
Note that the result won't exactly be {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}}; it'd be more like {{H, E, L, L, O}},{{W, O, R, L ,D}}.
You need an array of arrays
char[][] arr = new char[5][];
arr[0] = a.toCharArray();
char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();
What if a and b are not of the same length ? Your method and the ones proposed by others are very limited/specific and not flexible. Try this instead to make abstraction of the length of the String.
ArrayList<char[]> array = new ArrayList();
String a = "HELLO";
String b = "WORLD";
array.add(a.toCharArray());
array.add(b.toCharArray());
I'm extremely stuck here.
How would I convert a String array to a Char array?
I know of:
char[] myCharArray = myStringArray.toCharArray();
But obviously that doesn't work.
How would I do this?
You need to use a 2d/jagged array.
char[][] char2dArray = new char[myStringArray.length()][];
for ( int i=0; i < myStringArray.length(); i++) {
char2dArray[i] = myStringArray[i].toCharArray();
}
Here's one way to grab all the chars from all the strings in a single char array, if that's what you meant with the question:
String[] strArray = {"ab", "cd", "ef"};
int count = 0;
for (String str : strArray) {
count += str.length();
}
char[] charArray = new char[count];
int i = 0;
for (String str : strArray) {
for (char c : str.toCharArray()) {
charArray[i++] = c;
}
}
System.out.println(Arrays.toString(charArray));
=> [a, b, c, d, e, f]
You need to iterate through your String array converting every string in the string array to a char and then add that new char to your char array.
Assuming that a myStringArray is an array of Strings you would have to first iterate through this array extracting each individual String before converting the String to an array of chars.
for example
for (String str : myStringArray) {
{
char[] myCharArray = myStringArray.toCharArray();
// do something with myCharArray
}
I've been trying to split an string by a character and store each split value inside an array.
In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :
String t[] = new String[10];
for (int i = 0; i < rs.size(); i++) {
t = null;
t = rs.get(i).split("#");
}
But the whole split line is passed to an index of the array like:
String x = "Hello#World" -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)
My question is that how can store each spit element in an index of the array like :
t[0] = "Hello"
t[1] = "World"
It sounds like your trying to loop through a list, split them then add the arrays together? What your defining as the problem with the .split method is exactly what the split method does.
ArrayList<String> rs = new ArrayList<>();
rs.add("Hello#World");
rs.add("Foo#Bar#Beckom");
String [] t = new String[0];
for(int i=0;i<rs.size();i++) {
String [] newT = rs.get(i).split("#");
String [] result = new String[newT.length+t.length];
System.arraycopy(t, 0, result, 0, t.length);
System.arraycopy(newT, 0, result, t.length, newT.length);
t = result;
}
for(int i=0;i<t.length;i++) {
System.out.println(t[i]);
}
Works just find output is:
Hello
World
Foo
Bar
Beckom
public class Test {
public static void main(String[] args) {
String hw = "Hello#World";
String[] splitHW = hw.split("#");
for(String s: splitHW){
System.out.println(s);
}
}
}
This produced following output for me:
Hello
World
Try this way:
String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World
It is always good to test beforehand if the string contains a #(in this case), just use String#contains().
if (string.contains("#")) {
// Split it.
} else {
throw new IllegalArgumentException(message);
}
why are you using a loop when the problem is already solved in java..
try this
String x = "Hello#World";
String[] array = x.split("#", -1);
System.out.println(array[0]+" "+array[1]);