I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?
Related
how to remove "," in below string specified at s[0,2] location(818001,818002)(151515,151515) and store again to string []
String[] s = {"818001,818002","121212","151515,151515"};
You should explain more detailed your problem.
I think what you want is this:
s = '(818001,818002)(151515,151515)' //the string you have.
s = s.replace(')(',',').replace('(','').replace(')','');// output "818001,818002,151515,151515"
final_string = s.split(','); //output (4) ["818001", "818002", "151515", "151515"]
If you need to remove a comma (or any other char for that matter) in your String array indices the simplest is to iterate through the array and use String.replace():
String[] s = {"818001,818002","121212","151515,151515"};
for(int i=0; i<s.length; i++) {
s[i] = s[i].replace(",", "");
}
System.out.print(Arrays.toString(s)); // [818001818002, 121212, 151515151515]
So i'm trying to reverse a sentence and even though I don't have any errors when compiling, it tells me my reverse sentence is out of bounds.
-It should work like this: "hello, world!" --> !dlrow ,olleh"
Said code:
String sentence="this is a sentence!";
String reverseSentence=sentence;
for(int counter=0;counter<sentence.length();counter++)
{
char charToReplace,replaceChar;
charToReplace = reverseSentence.charAt(counter);
replaceChar = sentence.charAt(sentence.length()-counter);
reverseSentence=reverseSentence.replace(charToReplace, replaceChar);
System.out.println(reverseSentence);
}
The reason for the exception you are getting is that in sentence.charAt(sentence.length()-counter), sentence.length()-counter is out of bounds when counter is 0. Should be sentence.length()-1-counter.
However, as Tunaki commented, there are other problems with your code. I suggest you use a StringBuilder to construct the reversed String, instead of using replace (which would replace any occurrence of the first character with the second character).
You can use character arrays to implement your requirement like this,
String sentence = "ABDEF";
char[] firstString = sentence.toCharArray();
char[] reversedString = new char[sentence.length()];
for (int counter = 0; counter < sentence.length(); counter++) {
reversedString[counter] = firstString[sentence.length() - counter -1];
}
System.out.println(String.copyValueOf(reversedString));
It doesn't show you an error because the Exception concerning the indexes happen at RunTime.
Here :
replaceChar = sentence.charAt(sentence.length()-counter);
You're trying to access index 19 of your String (19-0). Replace it with :
replaceChar = sentence.charAt(sentence.length()-counter-1);
I'd recommend to use a StringBuilder in your situation though.
Either use the reverse() method :
String sentence = "this is a sentence!";
String reversed = new StringBuilder(sentence).reverse().toString();
System.out.println(reversed); // Prints : !ecnetnes a si siht
Or use the append() method for building your new String object. This uses less memory than using a String because it is not creating a new String object each time you're looping :
String sentence = "this is a sentence!";
StringBuilder reversed = new StringBuilder();
for (int i = 0 ; i < sentence.length() ; i++){
reversed.append(sentence.charAt(sentence.length() - 1 - i));
}
System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht
It maybe better to do it without any replacement, or for loop. It you create a char array from the string, reverse the array, then create a string from the reversed array this would do what you've asked without any moving parts or replacements. For example:
String hw = "hello world";
char[] hwChars = hw.toCharArray();
ArrayUtils.reverse(hwChars);
String wh = new String(hwChars);
System.out.println(wh);
Just split the String at each whitespace and put it in String array and then print the array in reverse order
public static void main(String[] args) {
String sentence = "this is a sentence!";
String[] reverseSentence = sentence.split(" ");
for (int i = reverseSentence.length-1; i >= 0; i--) {
System.out.print(" " + reverseSentence[i]);
}
}
I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5
If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well
For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.
Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5
I tried to make a program that separates characters.
The question is:
"Create a char array and use an array initializer to initialize the array with the characters in the string 'Hi there'. Display the contents of the array using a for-statement. Separate each character in the array with a space".
The program I made:
String ini = "Hi there";
char[] array = new char[ini.length()];
for(int count=0;count<array.length;count++) {
System.out.print(" "+array[count]);
}
What should I do to fix this problem?
Here's how you convert a String to a char array:
String str = "someString";
char[] charArray = str.toCharArray();
I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.
Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt() in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
char array[] = new String("Hi there").toCharArray();
for(char c : array)
System.out.print(c + " ");
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
Instead of above way u can achieve the solution simply by following method..
public static void main(String args[]) {
String ini = "Hi there";
for (int i = 0; i < ini.length(); i++) {
System.out.print(" " + ini.charAt(i));
}
}
You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.
Another easy way is that you use string literal and convert it to charArray in declaration itself.
Something like this -
char array[] = "Hi there".toCharArray();
//Print with white spaces
for(char c : array)
System.out.print(c + " ");
I have got a Java String as follows:
C|51199120|36937872|14261248|0.73|I|102398308|6240560|96157748|0.07|J|90598564|1920184|8867 8380|0.0
I want split this using regex as String arrays:
Array1 = C,51199120,36937872,14261248,0.73
Array2 =I,102398308,6240560,96157748,0.07
Array3 =J,90598564,1920184,88678380,0.03
Can Anybody help with Java code?
I don't think it's that simple. You have two things you need to do:
Break up the input string when you encounter a letter
Break up each substring by the pipe
I'm no regex expert, but I don't think it can be a single pattern. You need two and a loop over the substrings.
You can easily split your string on subcomponents using String.split("\\|"), but regexes won't help you to group them up in different arrays, nor will it help you to convert substrings to appropriate type. You'll need a separate logic for that.
Use String.split() method.
String []ar=str.split("(?=([A-Z]))");
for(String s:ar)
System.out.println(s.replace("|",","));
Simpler to just split then loop.
More or less:
String input = ...
String[] splitted = input.split("|");
List<String[]> resultArrays = new ArrayList<String[]>();
String[] currentArray = null;
for (int i = 0; i < splitted.length; i++) {
if (i % 5 == 0) {
currentArray = new String[5];
resultArrays.put(currentArray);
}
currentArray[i%5] = splitted[i];
}