How to remove first string and comma from a text file - java

!
I have a text, the content looks like [1,'I am java, and I am happy, I am.....'], I want to remove the first integer and the comma. When I was run the code above, but the result start with last comma: I am......

If you only want to remove commas from a String, you can use String.replaceAll(",",""); If you want to replace them by spaces, use String.replaceAll(","," "):
while ((line = br.readLine()) != null) {
contents.append(line.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.

You need to use the indexOfReturns the index within this string of the first occurrence of the specified character, starting the search at the specified index..
lastIndexOf Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
System.out.print(s.substring(s.indexOf(",")+1));

Use this following code as:
System.out.println(line.substring(2));
sub string takes the beginning index as a parameter and splits the string from that index to till the end.

Note that you are using lastIndexOf(). Use indexOf() to get the first index as shown below.
System.out.println(test.substring(line.indexOf(',')+1));

I'm taking your String literially, but you could use String#replaceFirst, for example...
String text = "[1,'I am java, and I am happy, I am.....']";
text = text.replaceFirst("\\[\\d,", "[");
System.out.println(text);
Which outputs...
['I am java, and I am happy, I am.....']
If you want to update the file, you are either going to have to read all the lines into some kind of List (modifying them as you please) and once finished, write the List back to the file (after you've closed it after reading it).
Alternatively, you could write each updated line to a second file, once you're finished, close both files, delete the first and rename the second back in it's place...

Try This code:
String[] s=line.splite(",");
String m="";
for(int i=1;i<s.length;i++)
{
String m=m+s[i];
}
br.append(m);

String input = "[1,'I am java, and I am happy, I am.....']";
//Getting String after first comma
String output = StringUtils.substringAfter(input, ",");
System.out.println("Output:"+output);
//replacing commas;
System.out.println("Final o/p:"+StringUtils.replace(output, ",",""));
You can use methods in StringUtils Class for string manipulations. For using StringUtils methods, you need to import apache-commons-lang.jar file. Using this API you can manipulate many String related methods. For more details, you can see the link
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

Related

Take first half of first string, and put it at beginning of second string based on user input

I am at the beginning chapters in my Java I class. This seems beyond what I have learned thus far.
I have to ask a user to input the first string. It could be anything. Then they have to input a second string. I have to take the first half of the first string and place it in front of the second string, then the other half of the first string and place it at the end of the first string. For example:
Enter something: ----
Enter something: word
Output: --word--
The only thing I've learned up until now is concatenation, indexes, and getting length. I have not learned arrays, if they can be relevant to this. What methods would I use to split this string up when I only know the strings after the user enters them? Even just informing me of unknown method calls would lead me in the right direction. I don't want (and can't) copy anyone's code.
Based on your example this is how you achieve that:
String firstString = "----"; //this should be read in from the user input.
String secondString = "word"; //this too should be read in from the user.
String finalString = firstString.substring(0,firstString.length()/2)+secondString+firstString.substring(firstString.length()/2,firstString.length());
Test code here
You should look into the Java StringAPI for substring. This will help you understand the code above.
You can use the substring method of the String class
something like this should work:
int idxMiddle = (string1.length()-1)/2;
string1.substring(0,idxMiddle) + string2 + string1.substr(idxMiddle);

Reading a line from a text file Java

I am trying to read a line from a file using BufferedReader and Scanner. I can create both of those no problem. What I am looking to do is read one line, count the number of commas in that line, and then go back and grab each individual item. So if the file looked like this:
item1,item2,item3,etc.
item4,item5,item6,etc.
The program would return that there are four commas, and then go back and get one item at a time. It would repeat for the next line. Returning the number of commas is crucial for my program, otherwise, I would just use the Scanner.useDelimiter() method. I also don't know how to return to the beginning of the line to grab each item.
Why not just split the String. The split method accepts a delimiter (regex) as an argument and breaks the String into a String[]. This will eliminate the need to return to the beginning.
String value = "item1,item2,item3";
String[] tokens = value.split(",");
To get the number of commas, just use, tokens.length - 1
String.split() Documentation
Split() can be used to achieve this
eg:
String Line = "item1,item2,item3"
String[] words =Line.split(",");
If you absolutely must know the number of commas, a similar question has already been answered:
Java: How do I count the number of occurrences of a char in a String?

String.contains() when reading from file

I am reading from a file line by line and then I want to check if that string contains another string so I use String.contains method but it returns always false.
I have tried to split the input line (and then using String.contains or String.equals) since the word to be checked is the first of the line.
The string I want to check is <now> and doing the splitting I have noticed that even when the line contains it I get false.
The strange fact is the string is printed out correctly but its length is bigger than the string <now>(even if I used replace to be sure there were no spaces) and I guess that is my problem. I am thinking it depends on the encoding of file but if so, is there any solution?
The file is the output of another Program (Praat) so I can not save it in another way.
line = inFile2.nextLine();
String[] w = line.split("[\t\\s]");
String checking = w[0];
checking.replace(" ","");
checking.replace("/t","");
String st ="<now>";
System.out.println(!checking.equals(st)); //returns always true
System.out.println(st.length()); //returns 5
System.out.println(checking.length()); //returns 11
System.out.println(checking); //it prints <now> correctly
The string in input is like: <now> 236 62 elena information-relation
Strings are immutable :
Note: The String class is immutable, so that once it is created a
String object cannot be changed. The String class has a number of
methods, some of which will be discussed below, that appear to modify
strings. Since strings are immutable, what these methods really do is
create and return a new string that contains the result of the
operation.
So it should be :
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
Or even better (method chaining) :
Checking = Checking.replace(" ","").replace("/t","");
Also please respect naming conventions.
String is immutable so you need to assign.
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
To make it shorter you can also do this:
String Checking = W[0].replace(" ", "").replace("/t", "");
Of course this depends on your preferences.
I solved re-saving the text file using UTF-8 encoding.

converting a String into a String array in Java

I simply cannot find how to do this.
so, I have a String that will be something like this:
do this
then do that
then more of this
and I need to turn this into an array of strings. where every new line is needs to be a separate entry in the array. I need this done so I can process every line or command separately. I can't enter it directly into an array because this is loaded from a text document, and there is some code that removes comments and unnecessary empty lines, and a few more things with the string before it needs to become an array.
thanks in advance!
String s = "do this\nthen do that\nthen more of this";
String[] split = s.split("\n");
Try this:
string.split("(?m)\n");

How to avoid triggering an ArrayIndexOutOfBoundsException while parsing empty positions in a line of CSV?

String[] values = line.split(",");
Long locId = Long.parseLong(replaceQuotes(values[0]));
String country = replaceQuotes(values[1]);
String region = replaceQuotes(values[2]);
String city = replaceQuotes(values[3]);
String postalCode = replaceQuotes(values[4]);
String latitude = replaceQuotes(values[5]);
String longitude = replaceQuotes(values[6]);
String metroCode = replaceQuotes(values[7]);
String areaCode = replaceQuotes(values[8]);
//...
public String replaceQuotes(String txt){
txt = txt.replaceAll("\"", "");
return txt;
}
I'm using the code above to parse a CSV with data in this format:
828,"US","IL","Melrose Park","60160",41.9050,-87.8641,602,708
However, when I encounter a line of data such as the following I get java.lang.ArrayIndexOutOfBoundsException: 7
1,"O1","","","",0.0000,0.0000,,
Does this mean that any time I even try to access the value at values[7], an Exception will be thrown?
If so, how do I parse lines that don't contain data in that position of the text line?
First of all, String.split() is not a great CSV parser: it doesn't know about quotes and will mess up as soon as one of your quoted values contains a comma.
That being said, by default String.split() leaves out empty trailing elements. You can influence that by using the two-argument variant:
String[] values = line.split(",", -1);
-1 (or any negative value) means that the array will be as large as necessary.
Using a positive value gives a maximum amount of splits to be done (meaning that everything beyond that will be a single value, even if it contains a comma).
0 (the default if you use the one-argument value) means that the array will be as large as necessary, but empty trailing values will be left out of the array (exactly as it happens to you).
As a general rule you should never, ever hack up your own (faulty) parser if a working one already exists. CSV is not easy to parse correctly, and String.split will not do the job since CSV allows , to be used between "'s without working as separaters.
Consider using OpenCSV. This will solve both the problem you have now and the problem you will face when a user uses a , as part of the data.

Categories