I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!
Related
I have to convert a binary number to a hex number. The way I have decided to do this is to split the binary string into several strings of length 4 and assign each string its corresponding value in hex number (i.e. 1000 = 8, 1101 = D).
I have seen several question asking for a way to split a string into strings of size 4 the same thing but all of those solutions used a regex that gave a single string. For example I found this line of code in a solution:
System.out.println(Arrays.toString("String".split("(?<=\G.{4})")));
When I tried to use it with the binary number "10011000", I got "[1001, 1000]" but as a single string (the brackets, comma, and blank space were included as characters) and I was left with the same problem, how do I split a string.
Is there a way to split a string into an array of smaller strings?
You can try making the string a char array and then into another array of strings, add each 4 characters of the char array.
Try this:
String BinaryNumber = "10011010";
char[] n = new char[BinaryNumber.length()];
for(int i=0; i<BinaryNumber.length(); i++){
n[i] = BinaryNumber.charAt(i);
}
String str;
String[] NumberArray = new String[(BinaryNumber.length())/4];
int count = 0;
for(int i=0; i<BinaryNumber.length(); i+=4){
str = String.valueOf(n[i])+String.valueOf(n[i+1])+String.valueOf(n[i+2])+String.valueOf(n[i+3]);
NumberArray[count] = str;
count++;
}
I think this might be the solution, though it will only work if the length of the BinaryNumber is divisible by 4.
Try it like this.
String binaryNumber = "110101111";
// first make certain the binary string is a multiple of length four so
// pad on the left with 0 bits.
binaryNumber = "0".repeat(3 - (binaryNumber.length()+3) % 4)
+ binaryNumber;
// Then you can just split it like this as you described.
String[] groups = binaryNumber.split("(?<=\\G.{4})");
for (String v : groups) {
System.out.println(v);
}
prints
0001
1010
1111
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
It's a very simple problem but at the moment my brain is fried from working on other parts of this project so I need help. I have a string of a size of a multiple of 16(example: size 16, 32, 48 etc.) I need to break that string into smaller strings of length 16 and place them into an array of size string.length()/16
For example we'll say my string(appendSourceBinary) is: "1000101101001001"
Here's my non working code:
String[] holding = new String[appendSourceBinary.length()/16];
int counter;
for(int z = 0; z < appendSourceBinary.length(); z++){
holding[z] = appendSourceBinary.substring(z, z+16);
}
There is a regex to do this just using split:
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
The regex splits on points in the string proceeded (asserted using a look behind) by the end of the last match (\G) followed by 16 characters (.{16}). Conveniently, \G is initially set to start of input.
Some test code:
String appendSourceBinary = "A234567890123456B234567890123456C234567890123456";
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
Arrays.stream(array).forEach(System.out::println);
Output:
A234567890123456
B234567890123456
C234567890123456
You could do it in two lines, without a loop, like this:
String appendSourceBinary = "10101010101010101010101010101010";
String[] split = appendSourceBinary.replaceAll("([01]{16})", "$1x").split("x");
I've used a regular expression search and replace to find each group of sixteen characters in the string and to replace them with themselves followed by an x. Then I've split the string on the x, leaving an array containing the groups of 16 characters.
If you add a simple loop to output the results:
for (int i = 0; i < split.length; i++)
System.out.println(split[i]);
you'll find the output is
1010101010101010
1010101010101010
Which is the original 32 char string I used split in two 16 char strings. Any remainder will be returned as the last element of the array. If there are less than 16 chars in the input string they'll be returned as the first and only array entry.
I need to extract several integers from a string that looks like this:
22:43:12:45
I need to extract 22, 43, 12, and 45 as separate integers. I need to use string methods or scanner methods to read up until : and extract the 22. Then read between the first : and second : to give me 43, and so on.
I can extract up to the first : no problem, but I down know what to do thereafter.
Any help would be much appreciated.
String[] parts = str.split(":");
int[] numbers = new int[parts.length];
Iterate over this String array to get an array of integers:
int index = 0;
for(String part : parts)
numbers[index++] = Integer.parseInt(part);
You should look at String.split method . Given a regular expression, this methods splits the string based on that. In your case the regular expression is a ":"
String s ="22:43:12:45";
int i =0;
for (String s1 : s.split(":")) { // For each string in the resulting split array
i = Integer.parseInt(s1);
System.out.println(i);
}
The split returns a string array with your string separated. So in this case , The resulting string array will have "22" on the 0th position, "43" on the first position and so on. To convert these to integers you can use the parseInt method which takes in a string and gives the int equivalent.
You can use only indexOf and substring methods of String:
String text = "22:43:12:45";
int start = 0;
int colon;
while (start < text.length()) {
colon = text.indexOf(':', start);
if (colon < 0) {
colon = text.length();
}
// You can store the returned value somewhere, in a list for example
Integer.parseInt(text.substring(start, colon)));
start = colon + 1;
};
Using Scanner is even simpler:
String text = "22:43:12:45";
Scanner scanner = new Scanner(text);
scanner.useDelimiter(":");
while (scanner.hasNext()) {
// Store the returned value somewhere to use it
scanner.nextInt();
}
However, String.split is the shortest solution.
Make a regex like
(\d\d):(\d\d):(\d\d):(\d\d)
I have split a string into an array every time a letter appeared, however I now want to split each string in the array into more arrays went another letter appears, adding an array below each split with the letter removed.
Here is my code:
private String input = "118u121u23n24"
private int y = 0;
private String[] split_main = new String[100];
private void split_u(){
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
split_main[y] = split[x];
if(split.length>x+1)
split_main[y+1] = "+";
y +=2;
}
This splits my string into an array like this - creates a new array every time "u" appears and adds a plus
118
+
121
+
23n24
I now want to go through each of these arrays and look for the letter n and put it on a separate line so this will be the new array. However every time I have tried this I have got errors because I don't seem to be able to use the Split method again on the array. If using split is not possible then is there another way to do it?
118
+
121
+
23
n
24
Thanks in advance for any help.
Try this
String[] split = input.split("u|n");
u|n means that split string with by u or n, simply split string by two separator
while you want to add different separator in two levels you should write code like this.
String input = "118u121u23n24";
String[] s2;
ArrayList<String> main = new ArrayList<String>();
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
s2 = split[x].split("n");
for(int k=0; k<s2.length; k++){
main.add(s2[k]);
if(s2.length>k+1)
main.add("n");
}
if(split.length>x+1)
main.add("+");
}
// print main array to test
for(int i=0;i<main.size();i++)
System.out.println(main.get(i));
I'd suggest that you simply split on all the letters at once, using a regex:
String[] split = input.split("(+|n)");
If you require the intermediate steps, then the only way to do it is to iterate through the first split, building an array of results of splitting on the second letter. If you want to do this for multiple split patterns (not just "+" and "n"), you will need a general purpose procedure. Here's sample code:
/**
* Replaces one element of a list of strings with the results of
* splitting that element with a given pattern. A copy of the pattern
* is inserted between the elements of the split.
* #param list The list of elements to be modified
* #param pattern The pattern on which to split
* #param pos The position of the element to split
* #return The number of additional elements inserted. This is the amount by
* which the list grew. If the element was not split, zero is returned.
*/
int splitElements(List<String> list, String pattern, int pos) {
String[] split = list.get(pos).split(pattern);
if (split.length > 1) {
list.set(pos++, split[0]);
for (int i = 1; i < split.length; ++i) {
list.add(pos++, pattern);
list.add(pos++, split[i]);
}
} // else nothing to do
return (split.length << 1) - 1;
}
Then you would call this with each character with which you want to split:
private String input = "118u121u23n24";
private ArrayList<String> split_main = new ArrayList<String>();
split_main.add(input);
splitElements(split_main, "+", 0);
for (int i = 0; i < len; ++i) {
i += splitElements(split_main, "n", i);
}
It's possible. Use List instead of array to make inserting new items easy.
If you want arrays only, do it in two passes: first, iterate over input and count how many more cells you need because of n, then create new array of proper size and copy input contents to it, splitting along the way.