I have a problem with reading a txt file in Java. I have a File.txt (there is something like this:
Lalala
Java
C++
I want to 'convert' it into an array (for example for tab[0][0] will be L, then tab[0][1] will be a, etc.).
How can I do this?
If you have a String, you can convert it into an array of single characters by calling String.toCharArray();
First, split the String up into individual words...
String myExample = "Lalala Java C++";
String[] lines = myExample.split(" ");
Then split the individual lines into characters...
String myFirstLine = lines[0];
char[] letters = myFirstLine.toCharArray();
If you need it in a 2D array, you could then do something like this (this is a full example)...
String myExample = "Lalala Java C++";
String[] lines = myExample.split(" ");
char[][] myArray = new char[lines.length][0];
for (int i=0;i<lines.length;i++){
myArray[i] = lines[i].toCharArray();
}
This will assign the letters of line 1 to myArray[0][0], myArray[0][1], etc, and the letters of line 2 to myArray[1][0], myArray[1][1], etc, as you requested.
If what you want is a bidimensional array, the problem is that the width of the array need to be the length of the bigger word. I think is not a good practice.
Maybe if you create a list of arrays, it can be better:
List<char[]> arrays = new ArrayList<char[]>();
String[] words = fullText.split(" "); //or split("\\s+") if the text contains many lines or many spaces between the words
for(String word: words){
char[] charsOfWord = word.toCharArray();
arrays.add(charsOfWord);
}
This way, to access the frist character in the first word:
System.out.println(arrays.get(0)[0]);
Related
Hello I am trying to figure out how I would read a line in a comma separated text file and store each word that is separated by a comma in the file into a separate array.
For example if the line in the file was
Dog, blue, large
Then I would like to have 3 different arrays that store one word from the list. So would array 1 would store Dog, array 2 stores blue, and array 3 stores large.
Thanks
String input = "Dog, blue, large";
StringTokenizer st = new StringTokenizer(input, ",");
String[] array = new String[st.countTokens()];
for (int i = 0; i < array.length; i++) {
array[i] = st.nextToken().trim();
}
Use String utils for removing spaces and split the text.
String text = "Dog, blue, large";
String[] split = text.trim().split(",");
.trim() removes the whitespace and .split(",") splits the string.
This might have been asked before, but I spent some time looking, so here's what I have.
I have a string containing an array:
'["thing1","thing2"]'
I would like to convert it into an actual array:
["thing1","thing2"]
How would I do this?
You could create a loop that runs through the whole string, checking for indexes of quotes, then deleting them, along with the word. I'll provide an example:
ArrayList<String> list = new ArrayList<String>();
while(theString.indexOf("\"") != -1){
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
list.add(theString.substring(0, theString.indexOf("\"")));
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
}
I would be worried about an out of bounds error from looking past the last quote in the String, but since you're using a String version of an array, there should always be that "]" at the end. But this creates only an ArrayList. If you want to convert the ArrayList to a normal array, you could do this afterwards:
String[] array = new String[list.size()];
for(int c = 0; c < list.size(); c++){
array[c] = list.get(c);
}
You can do it using replace and split methods of String class, e.g.:
String s = "[\"thing1\",\"thing2\"]";
String[] split = s.replace("[", "").replace("]", "").split(",");
System.out.println(Arrays.toString(split));
For my program, the input from the user will be something like this:
{1,2,3} {1,2} {4,5,6}
There can be multiple { } with any number of ... numbers inside.
I already made a 2 dimensional array with an array for each sequence of numbers: {}
I am having troubling splitting them into their respective arrays so it will be something like this:
Array[0] = ["1","2","3"]
Array[1] = ["1","2"]
Array[2] = ["4","5","6"]
How would i split it like that? i dont know if i can split this string into n number of strings since the number of sequences depends on user.
Split the string on " " (space), and from there remove the curly brackets (perhaps take a substring, from index 1 to index length-1). Then split on comma. That should return a string array containing numbers. From there parse the strings to integers, and store in an integer array.
This code will help you
public class T {
public static void main(String[] args) {
String s = "{1,2,3} {1,2} {4,5,6}";
String[] mainArray = s.split(" ");
String[][] result = new String[mainArray.length][];
int count = 0;
for (String t : mainArray) {
result[count] = t.split(",");
count++;
}
}
}
var x = "{1,2,3} {1,2} {4,5,6}";
var y = x.split(" ");
var k =[];
for(var i = 0; i < y.length; i++){
k.push((y[i].substring(1,y[i].length-1)).split(","));
}
Well, this be how you would do it in javascript, algorithm.(my bad mis-read the tag)
K will be the final array.
Create a collection of arrays (of the type the input arrays will be, if known).
Split the array on "{".
With the resulting array, you remove the "}" from each string and split it on ",".
Then iterate over the resulting string array, parsing its contents and building an array of your entry type.
Finally, add that array to your collection.
This assumes there are no sub-arrays, true for your sample input. It does not assume the user added spaces between the given arrays, however; that is something I wouldn't trust a user to remember.
how can the elements inside a String separated by blank spaces be sorted.I have the following String:
temp = abcd bcda gfre dfgre fwft efwe
//temp.size() gives 30
//after the sort temp should look like ie temp = abcd bcda dfgre efwe fwft gfre
I need to sort the elements in temp in the least possible time.Please note that the size of temp that i am dealing with is of the order of 10 to the power 7.I forgot to mention that i have tried Collections.sort and Array.sort which are taking too much time than required.What i require is a faster algorithm than that?
Split the String using .split(seperator)
Sort using Collections Arrays.sort()
String [] array = temp.split("\\s+"); // split by whitespace
Arrays.sort(array); // sort using mergesort with insertionsort
StringBuilder sb = new StringBuilder(temp.length());
for(String s : array){
sb.append(s).append(" ");
}
temp = sb.toString(); // assign temp the new string
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!