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'm trying to implement in java this little project: I want to rename the episodes of an entire season in a series using a text file that has the names of all the episodes in that season.
To that end I wrote a code that reads the text file and stores every line of text (the name of an episode) as a string array, where every element of the array stores the name of one episode. Also, I wrote a code that takes the FIRST element of that array (an array called arrayLines[]) and renames a given file.
This code works like a charm.
What I want to do next is to create a char array for every element in the string array arrLines[].
The pseudo-code i'm thinking to implement is something like this:
for(int i=0; i<arrLines.length; i++){
char line_i+1[] = arrLines[i];
}
and thus getting many arrays with the names line_1, line_2,..., line_arrLines.length, with the name of every episode stored as a char array.
How can I implement something like this?
Just use a 2-dimensional char array:
char[][] lines = new char[arrLines.length][];
for (int i = 0; i < arrLines.length; i++) {
lines[i] = arrLines[i].toCharArray();
}
If you have Java 8, you can use Streams:
char[][] lines = Arrays.stream(arrLines)
.map(String::toCharArray)
.toArray(char[][]::new);
You can use the String toCharArra method.
for(int i = 0; i < strArray.length; i++) {
char[] charArray = strArray[i].toCharArray();
}
There is a string[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"} which needs to be split on the basis of , and -. The values aa,dd,aa should be stored in one list whereas bb,hh in another list. I have written this code snippet:
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split(",");
for(int j=0;j<newArr.length;j++){
resultArr = newArr[j].split("-");
appList.add(resultArr[0]);
prodList.add(resultArr[1]);
rolList.add(rresultArr[2]ol);
}
Above approach could be better if we do arr[i].split in another way so that we can run only one loop but I could not achieve that so far.
I wanted to know is there any best way to achieve the requirement.
You don't need to split it using , ,since it's not part of the String but part of the String array declaration syntax,just split it with a -
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split("-");
appList.add(newArr[0]);
prodList.add(newArr[1]);
rolList.add(newArr[2]);
}
How do i read a file and determine the # of array elements without having to look at the text file itself?
String temp = fileScan.toString();
String[] tokens = temp.split("[\n]+");
// numArrayElements = ?
Use the length property of the array:
int numArrayElements = tokens.length;
The proper expression is tokens.length. So, you can assign numArrayElements like this:
int numArrayElements = tokens.length;
This counts the number of elements in the tokens array. You can count the number of elements in any array in the same way.
How would I remove the chars from the data in this file so I could sum up the numbers?
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to do this so for every line it will remove all the chars but not ints.
The following code might be useful to you, try running it once,
public static void main(String ar[])
{
String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";
int sum=0;
String[] spl = s.split(",");
for(int i=0;i<spl.length;i++)
{
try{
int x = Integer.parseInt(spl[i]);
sum = sum + x;
}
catch(NumberFormatException e)
{
System.out.println("error parsing "+spl[i]);
System.out.println("\n the stack of the exception");
e.printStackTrace();
System.out.println("\n");
}
}
System.out.println("The sum of the numbers in the string : "+ sum);
}
even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers
You need to split each line into a String array and parse the numbers starting from index 1
String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
int n = Integer.parseInt(arr[i]);
...
try this:
String input = "Name,2,1,3,4,5,10,100";
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
You can make use of the split method of course, supplying "," as the parameter, but that's not all.
The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:
1) Put each line of the text file inside an ArrayList
2) For each line, Split to an array by using ","
3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line
4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)
5) use Integer.parseInt( iterated number as String ) and sum it up
There you go
Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)
Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.
Edit: here's the complete program:
class Foo {
static String input = "Name,2,1,3,4,5,10,100";
public static void main(String[] args) {
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
System.out.println(result);
}
}
(wow, I never wrote a program before that didn't import anything.)
And here's the output:
125
If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.
String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
sb.append(',').append(fields[i]);
line = sb.toString();
You could also use a Pattern (regular expression):
line = line.replaceFirst("[^,]*,", "");
Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.
There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:
I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
Add numbers to counters
Continue until end of file
Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:
Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
Iterating over the data 2 times instead of one (probably not the end of the world)
Suppose, format of the string is fixed.
String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";
At first, I would get rid of characters
Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
int sum = 0;
After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:
if (matcher.find()){
for (String ele: matcher.group(0).split(",")){
sum+= Integer.parseInt(ele);
}
}
System.out.println(sum);