Java String treatment with splitting - java

I need your help. I have a string with value "1,2,3,4,5,6,7,8,9,10".
What I want to do is take once first value ("1") only (substring (0, 1) for example) and then do a loop with the rest of values except the first value that I already take.
Maybe I have to create another String variable and set the values without first value to the second String variable and then create a loop? How to do that?

The easiest way would probably be to use String#split(String):
String str = "1,2,3,4,5,6,7,8,9,10";
String[] parts = str.split(",");
// Save the first part
String firstPart = parts[0];
// Iterate over the others:
for (int i = 1; i < parts.length; ++i) {
System.out.println (parts[i]); // Or do something useful with it
}

You can use split function.
String numbers = "1,2,3,4,5,6,7,8,9,10"; //Here your String
String[] array = numbers.split(","); //Here you divide the String taking as reference the ,
String number = array[0] //You will get the number 1
If you want to take the rest of the elements:
for(i = 1; i < array.length; i++)
System.out.println(array[i]);
I expect it will be helpful for you!

Related

Extracting integer from a string

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

Why isn't this code reversing user inputted text?

System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);
String x = sc1.nextLine();//user input
for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}
In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
System.out.print(x.substring(i, i+1));
}
substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
System.out.print(x.charAt(i));
}
As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
System.out.print(x.charAt(i));
}

Remove chars from string in Java from file

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);

Java indexOf returns -1

So I am reading in a line from a file, that looks like:
Snowman:286:355:10
And this is the first part of the code I wrote to separate the data and place it into arrays.
for (int i = 0 ; i<manyItems; i++)
{
a = 0;
temp = scan.nextLine();
System.out.println(temp);
b = temp.indexOf(':');
System.out.println(b);
items[i] = temp.substring(a,b);
System.out.println(items[i]);
System.out.println(temp);
a = b;
System.out.println(temp);
b = temp.indexOf(a+1,':');
System.out.println(b);
rawX[i] = temp.substring(a+1,b);
System.out.println(rawX[i]);
}
It separates "Snowman" places it into the array, however, when I try to find the second colon, indexOf() keeps returning -1. Does anyone know why it is not finding the second colon?
You could save all that code and use String#split to split the line:
String[] parts = temp.split(":");
I think you have the arguments backwards:
b = temp.indexOf(a+1,':');
Should be...
b = temp.indexOf(':', a+1);
From docs.oracle.com:
public int indexOf(int ch,
int fromIndex)
The first argument is the character, the second if the fromIndex.
Because you swapped the arguments of the indexOf call. It expects the character, then the index to start looking at. Remember that chars are ints, you're looking for the char 7 starting at the int value of ':'.
There's a method under String class that will handle the job for you. Split(regEx pattern) is what you may want to use. The following code will do the job you're trying to perform:
String input = "Snowman:286:355:10";
String tokens [] = input.split(":");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);

putting a value in a single cell through loop using poi in java

I have a String in the following format:
abcd|1|2,pqr|2|3......
I want to output the following in a single cell:
abcd|1|2
pqr|2|3
I am splitting the string on the , character.
The string value is coming from another loop
for(ActivityDTO activity : activityList) {
HSSFCell cell6 = dataRowAct.createCell(6);
String str[] = string.split(",");
for(int i = 0; i < str.length; i++) {
cell6.setCellValue(new HSSFRichTextString(str[i]+"\n"));
}
}
But in excel I only get the last value as the old value overwites.
It looks like you're repeatedly setting the value of cell6. It will end up being the value of whatever yoy set it as last, which matches up with the problem you're having. Depending on what you want to end up with, you need to change the cell that is being set in your for loop. i.e, change cell6 to something else depending on what i you're on.
You need to build a String (using a StringBuilder) then print the final result to the cell.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length; i++) {
sb.append(str[i] + "\n");
}
cell6.setCellValue(sb.toString());
As an alternative...
If you simply want to replace , characters with newlines, you can use String.replace() like this:
String s = "abcd|1|2,pqr|2|3";
cell6.setCellValue(s.replace(",", "\n"));
This replaces each occurrence of , with a newline.
I hope I'm right
You want the whole in one cell
abcd|1|2
so
String str[] = string.split(",");
int r=//row number
Row row=sheet.createRow(r);
for(int i = 0; i < str.length; i++) {
cell6.setCellValue(new HSSFRichTextString(str[i]+"\n"));
cell6=sheet.createRow(++r).createCell(/*cellnumber*/);
}
Because you are removing old value.
String s="";
for(int i=0;i<str.length;i++) {
s+=str[i]+"\n";
}
cell6.setCellValue(new HSSFRichTextString(s));
I don't know what is your cell6 here. Anyway the logic should be like:
cell6.setCellValue(cell6.getCellValue()+str[i]+"\n"));

Categories