Hi I am just starting to learn java and i am stuck on a problem.
The problem states that if we have a string S
S = "123:456:789"
We have to extract the numbers 123 ,456,789 separately and store them in different variables such as
int a=123
Int b=456
Int c=789
How can we do that?
You can split them by the : character and then save parse the Strings and save them in an array as follows:
String S = "123:456:789";
String[] arr = S.split(":");
int[] integers = new int[arr.length];
for(int i = 0; i < arr.length; i++)
integers[i] = Integer.parseInt(arr[i]);
You can split the string based on a delimiter into a string array. Once you have the string array you can access each array's element to get the specific values.
String S = "123:456:789"
String[] example = S.split(":");
Source: https://javarevisited.blogspot.com/2017/01/how-to-split-string-based-on-delimiter-in-java.html
Look at the method split() in String, and into Integer.parseInt().
You also need to look into Regular Expressions
I have a string, ie 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17. How do I get each value and convert it into an array? [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]. I can't find any suggestions about this method. Can help? I did try using regex, but it just simply remove ',' and make the string into one long sentence with indistinguishable value. Is it ideal to get value before and after ',' with regex and put it into []?
You could use following solution
String dummy = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] dummyArr = dummy.split(",");
Try this to convert string to an array of Integer.
String baseString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] baseArray = baseString.split(",");
int[] myArray = new int[baseArray.length];
for(int i = 0; i < baseArray.length; i++) {
myArray[i] = Integer.parseInt(baseArray[i]);
}
Java provides method Split with regex argument to manipulate strings.
Follow this example:
String strNumbers= "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] strNumbersArr= strNumbers.split(",");
You can convert an array of string in array of integer with Streams
int[] numbersArr = Arrays.stream(strNumbersArr).mapToInt(Integer::parseInt).toArray();
Use String.split() and you will get your desired array.
String s1="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] mumbers=s1.split(","); //splits the string based on comma
for(String ss:numbers){
System.out.println(ss);
}
See the working Example
String csv = "Apple, Google, Samsung";
String[] elements = csv.split(",");
List<String> fixedLenghtList = Arrays.asList(elements);
ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);
//ouput
[Apple, Google, Samsung]
if you want an int array
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] split = s.split(",");
int[] result = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
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've got a string, for example:
String code = new String("[199, 56, 120]")
My goal is to create and Array that contains only the numbers inside the [] and beetween commas;
In this case it would be for example:
array[0] = 199
array[1] = 56
array[2] = 120
Is possible to do something like this??
Thanks in advance.
You just need to use the split function.
Skip the [ and the ] and you can do something like this:
String input = "199 56 120";
String[] array = input.split(" ");
If you really want [ and the ] then you can use something like
input.replace("[", "");
input.replace("]", "");
To strip the string before you split it.
Edit
It doesn't matter what the format is or what the numbers are or how many they are, you simply edit the split definition according to the format, so if you're case is , then you simply use that as the split parameter.
String input = "[number, number, number]";
String sep = ", ";
String fixedInput = input.replace("[", "").replace("]", "");
String[] array = fixedInput.split(sep);
// array[0] contains first number.
// array[1] contains second number.
If you want an int[] array then you could do something like this:
int[] intArray = new int[array.length];
for(int i = 0; i < array.length; i++)
{
intArray[i] = Integer.parseInt(array[i]);
}
If you want a one-line solution:
String[] array = code.replaceAll("[^\\d ]", "").split(" ");
The in-line call to replaceAll() removes non-digits/spaces.
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 + " ");