I am reading each line in the text file, do some with the file and write back to same file using Java. And, position(index) of each value in the line is important. So I need to preserve the location of the each value.
How do I remove a "space" character at specific location(index)?
Say, below is the line that I read,
.... ABC 123.... --There are 3 spaces between ABC and 123
Basically, I want to make the above line written as 2 spaces between ABC and 123.
At first, I was just using replaceAll of String but that just shift the the values to right by one and still 3 spaces. So, I figure I need more than just replaceAll.
Now, I am getting a position of where ABC is found and just trying to remove that 1 space.
If you want to remove a single character, just use StringBuilder.deleteCharAt.
final int pos = ...;
str = new StringBuilder(str).deleteCharAt(pos).toString();
I explicitly advise you not to do the substring approach.
Can you not do a search for the whole string? The first parameter has three spaces and the second has two spaces
replaceAll("ABC 123", "ABC 123");
or if ABC is your key input
replaceAll("ABC ", "ABC ");
and the first parameter has 3 spaces and the second two after the ABC
Since you know the position n (zero based) of string s that you want to remove:
s = s.substring(0, n) + s.substring(n + 1);
You could just convert your string to a char array and loop it, but it's not a nice way to do it.
Or you could do:
myString = myString.substring(0,(position of first space))+
myString.substring((position of first space)+1, myString.length);
or something like that
Related
I have string where only a certain part should be selected. until i reach a character.
Ex. 5000 - 10000 i want only 5000 until the - or the white space.
input.replace("","");
What Regular expression should i be using.
Something like this:
final String beforeDash = input.split("-")[0].trim();
This should solve your problem:
String[] parts = input.split("-");
The string you are looking for is then in parts[0].
If you want to split on the whitespace instead of the dash, use string.split(" ").
You could try the below code which matches the first space or - upto the last character. Replacing those matched characters with an empty string will gave you the desired output.
input.replaceAll("[\\s-].*","");
You could also use string.split function.
String[] parts = input.split("[\\s-]");
System.out.println(parts[0]);
The above split function would split the input according to a space or a hyphen. Printing the index 0 from the splitted parts will give you the desired output.
I have a csv file that looks like this:
12,2014-10-09 06:00:00,2014-10-09 06:15:00,"","","","123,456","","9,999","",""
I was able to replace the comma inbetween the digits and all double quoutes using:
String test = rowData.replaceAll("([0-9]),([0-9])","$1$2").replaceAll("\"","");
I'm not sure if this is the best approach to do this (opinion is appreciatted). My problem is I need to remove the first value before the comma also, so basically my output needs to be something like this
Orig: 12,2014-10-09 06:00:00,2014-10-09 06:15:00,"","","","123,456","","9,999","",""
Need: 2014-10-09 06:00:00,2014-10-09 06:15:00,,,,123456,,9999,,
I'm not sure if another regex is needed to do this as I don't know how exactly or use something like lastindex or firstindex to remove the fist value of the comma??? thank you
EDIT: I just noticed I can't use ([0-9]),([0-9]) cause it also remove the comma for the datetime. :(. Proper question is how to replace the csv to remove the:
1. first value
2. quotes
3. comma between the digit and quotes
Try this:
String test = rowData.replaceAll("^[^,]+|,(?!(([^\"]*\"){2})*[^\"]*$|\"(?=,)|(?<=,)\"", "");
There are three alternations that are replaced with blank (ie removed):
everything up to and including the first comma
all commas within quotes (those not followed by an even number of quotes)
all quotes adjacent to (immediately after or before) commas
To match your expected output you can do something like
String str = "12,2014-10-09 06:00:00,2014-10-09 "
+ "06:15:00,\"\",\"\",\"\",\"123,456\",\"\",\"9,999\",\"\",\"\"";
str = str.substring(str.indexOf(',') + 1);
str = str.replaceAll("\"(\\d+),(\\d+)\"", "$1$2").replace("\"", "");
String expected = "2014-10-09 06:00:00,2014-10-09 06:15:00,,,,123456,,9999,,";
System.out.println(str.equals(expected));
Output is
true
Try this
test = test.substring(test.indexOf(",") + 1, test.length());
Reasons this is better than the other guys answer: less overhead, no need for regex for this!
Part of my application I encountered this problem. The String line variable contains 12.2 Andrew and I'm trying to split them separately but it doesn't work and comes with a NumberFormatException error. Could you guys help me on that please?
String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");
System.out.println(Double.valueOf.(data[0]));
Did you look at your data variable? It didn't split anything at all, since the condition never matches. You are looking for a place in the input immediately after a number and before a letter, and since there is a space in between this doesn't exist.
Try adding a space in the middle, that should fix it:
String[] data = line.split("(?<=\\d) (?=[a-zA-Z])");
Your split is not working, and not splitting the String.
Therefore Double.parseDouble is parsing the whole input.
Try the following:
String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
// System.out.println(Double.valueOf(data[0]));
// fixed
data = line.split("(?<=\\d).(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
System.out.println(Double.valueOf(data[0]));
Output
[12.2 Andrew]
[12.2, Andrew]
12.2
If you print content of data[0] you will notice that it still contains 12.2 Andrew so you actually didn't split anything. That is because your regex says:
split on place which has digit before and letter after it
which for data like
123foo345bar 123 baz
effectively can only split in places marked with |
123|foo345|bar 123 baz
^it will not split `123 baz` like
`123| baz` because after digit is space (not letter)
`123 |baz` before letter is space (not digit)
so regex can't match it
What you need is to "split on space which has digit before and letter after it" so use
String[] data = line.split("(?<=\\d)\\s+(?=[a-zA-Z])");
// ^^^^ - this represent one ore more whitespaces
Here's a problem I'm facing when I try to break my string (which I took as an input).
IDK why it is taking this extra 'space' in the beginning of the arrayTry.
Why: " H i ."? Why not "H i ."
Please help me out.
2) Furthermore, how can i take paragraph as an input?
How will the 'new line' be shown in the broken string array?
Thanks.
There is no extra space. That is just an empty String with a space behind it. Namely, the one you wrote in your loop:
System.out.println(arrayTry[i] + " ");
So, this means that arrayTry[0] is an empty String.
When you split on "", it will return an array of Strings, where there is one character per String, and apparently an extra empty String in the beginning and at the end.
To split on newlines, just write it using the \n escape character for newline:
String[] paragraphs = input.split("\n+");
Trim your string (ie remove leading and trailing spaces) before splitting.
String strng = input.nextline();
strng = strng.trim();
strng.split(" ");
I have a string like
String myString = "hello world~~hello~~world"
I am using the split method like this
String[] temp = myString.split("~|~~|~~~");
I want the array temp to contain only the strings separated by ~, ~~ or ~~~.
However, the temp array thus created has length 5, the 2 additional 'strings' being empty strings.
I want it to ONLY contain my non-empty string. Please help. Thank you!
You should use quantifier with your character:
String[] temp = myString.split("~+");
String#split() takes a regex. ~+ will match 1 or more ~, so it will split on ~, or ~~, or ~~~, and so on.
Also, if you just want to split on ~, ~~, or ~~~, then you can limit the repetition by using {m,n} quantifier, which matches a pattern from m to n times:
String[] temp = myString.split("~{1,3}");
When you split it the way you are doing, it will split a~~b twice on ~, and thus the middle element will be an empty string.
You could also have solved the problem by reversing the order of your delimiter like this:
String[] temp = myString.split("~~~|~~|~");
That will first try to split on ~~, before splitting on ~ and will work fine. But you should use the first approach.
Just turn the pattern around:
String myString = "hello world~~hello~~world";
String[] temp = myString.split("~~~|~~|~");
Try This :
myString.split("~~~|~~|~");
It will definitely works. In your code, what actually happens that when ~ occurs for the first time,it count as a first separator and split the string from that point. So it doesn't get ~~ or ~~~ anywhere in your string though it is there. Like :
[hello world]~[]~[hello]~[]~[world]
Square brackets are split-ed in to 5 different string values.