How to safely remove the commas on an ArrayList? - java

I have an Arraylist where I place float values.
xEvent.add(fileTimeStamp);
xEvent.add(x);
xEvent.add(zCSV + "\n");
String formatedString = xEvent.toString()
.replace("[", "") // remove the right bracket
.replace("]", "") // remove the left bracket
The problem is that the Arraylist places a comma to separate values. How can I get rid of this comma without getting rid of the comma that in some locales is used as the decimal mark? On the U.S. we use the period as the decimal mark, so removing all commas would work, however on countries where they use the comma as the decimal mark I would end up ruining the data.

I'm not sure you can errase the ',' from the to string without ruining the data, I would recomend using a for() to get the information
String formatedString="";
for(String s: xEvent){
formatedString += s;
}
Like this you will get all the information inside a String without the ']','[' or ','.
Hope it helps you.

You might want to look into using a StringBuilder in this case, for example:
StringBuilder builder = new StringBuilder();
builder
.append(fileTimeStamp)
.append(x)
.append(zCSV);
String formatedString = builder.toString();

Related

How to extract specific String values using regex

I am a newbie in regex, I want to extract values between commas but I don't know how.
I have values like this :
[1000, Value_to_extract, 1150370.5]
and I used this Technic to simplify it:
String val = "[1000, Value_to_extract, 1150370.5]";
String designation=val.replace("[", "").replace("]", "").trim();
It give's me this result :
1000, Value_to_extract, 1150370.5
I don't know how to extract only Value_to_extract
I tried : String designation=val.replace("[", "").replace("]", "").replaceAll(".*, ,.*", "").trim();
but i doesn't work .
Thank you for your help.
String input = "[1000, Value_to_extract, 1150370.5]";
String[] parts = input.replaceAll("\\[\\] ", "") // strip brackets and whitespace
.split(","); // split on comma into an array
String valueToExtract = parts[1]; // grab the second entry
Notes:
You might also be able to use a regex here, q.v. the answer by #Thomas, but a regex will become unwieldy for extracting values from a CSV string of arbitrary length. So in general, I would prefer splitting here to using a regex.
someting like this:
,[ ]?([0-9]+[.]?[0-9]+),
breakdown
, // literal ,
[ ]? // 0 or 1 spaces
([0-9]+[.]?[0-9]+) // capture a number with or without a dot
, // another litteral ,
https://regex101.com/r/oR7nI8/1
Here are some options:
String val = "[1000, Value_to_extract, 1150370.5]";
//you can remove white space by
String noSpaces = val.trim();
System.out.println(noSpaces);
//you can split the string into string[] settting
//the delimiting regular expression to ", "
String[] strings = noSpaces.split(", ");
//the strings[1] will hold the desired string
System.out.println(strings[1]);
//in the private case of val, only Value_to_extract contains letters and "_" ,
//so you can also extract it using
System.out.println(val.replaceAll("[^a-zA-Z_]", ""));
If val does not well represent the more general need, you need to define the need more precisely.

Looking for method to remove spaces on sides, change all letters to small with first letter as capital letter

I have been trying for a while to make a method which takes an user input and changes it so that potential spaces infront and after the text should be removed. I tried .trim() but doesnt seem to work on input strings with two words. also I didnt manage to make both first and second word have the first letter as Capital.
If user inputs the following string I want all separate words to have all small letters except for the first in the word. e.g: Long Jump
so if user inputs:
"LONG JuMP"
or
" LoNg JUMP "
change it to
"Long Jump"
private String normalisera(String s) {
return s.trim().substring(0,1).toUpperCase() + s.substring(1).toLowerCase();
}
I tried the method above but didnt work with two words, only if the input was one. It should work with both
To remove all spaces extra spaces you can do something like this
string = string.trim().replaceAll(" +", " ");
The above code will call trim to get rid of the spaces at the start and end, then use regex to replace everything that has 2 or more spaces with a single space.
To capitalize the first word, if you're using Apache's commons-lang, you can use WordUtils.capitalizeFully. Otherwise, you'll need to use a homebrewed solution.
Simply iterate through the String, and if the current character is a space, mark the next character to be uppercased. Otherwise, make it lowercase.
Split your problems into smaller ones:
You need to be able to:
iterate over all words and ignore all whitespaces (you can use Scanner#next for that)
edit single word into new form (create helper method like String changeWord(String){...})
create new String which will collect edited versions of each word (you can use StringBuilder or better StringJoiner with delimiter set as one space)
So your general solution can look something like:
public static String changeWord(String word) {
//code similar to your current solution
}
public static String changeText(String text) {
StringJoiner sj = new StringJoiner(" ");// space will be delimiter
try(Scanner sc = new Scanner(text)){
while (sc.hasNext()) {
sj.add(changeWord(sc.next()));
}
}
return sj.toString();
}
Since Strings are immutable and you cannot make in place changes you need to store it in a separate variable and then do your manipulations like this:
String s = " some output ";
String sTrimmed = s.trim();
System.out.println(s);
System.out.println(sTrimmed);
Change your code like this for the rest of your code as well.

String.replace() not replacing all occurrences

I have a very long string which looks similar to this.
355,356,357,358,359,360,361,382,363,364,365,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,368,369,313,370,371,372,373,374,375,376,377,378,379,380,381,382,382,382,382,382,382,383,384,385,380,381,382,382,382,382,382,386,387,388,389,380,381,382,382,382,382,382,382,390,391,380,381,382,382,382,382,382,392,393,394,395,396,397,398,399,....
When I tried using the following code to remove the number 382 from the string.
String str = "355,356,357,358,359,360,361,382,363,364,365,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,368,369,313,370,371,372,373,374,375,376,377,378,379,380,381,382,382,382,382,382,382,383,384,385,380,381,382,382,382,382,382,386,387,388,389,380,381,382,382,382,382,382,382,390,391,380,381,382,382,382,382,382,392,393,394,395,396,397,398,399,...."
str = str.replace(",382,", ",");
But it seems that not all occurrences are being replaced. The string which originally had above 3000 occurrences still was left with about 630 occurrences after replacing.
Is the capability of String.replace() limited? If so, is there a possible way of achieving what I need?
You need to replace the trailing comma as well (if one exists, which it won't if last in the list):
str = str.replaceAll("\\b382,?", "");
Note \b word boundary to prevent matching "-,1382,-".
The above will convert:
382,111,382,1382,222,382
to:
111,1382,222
I think the issue is your first argument to replace(), in particular the comma (,) before and after 382. If you have "382,382,383", you will only match the inner ",382," and leave the initial one behind. Try:
str.replace("382,", "");
Although this will fail to match "382" at the very end as it does not have a comma after it.
A full solution might entail two method calls thus:
str = str.replace("382", ""); // Remove all instances of 382
str.replaceAll(",,+", ","); // Compress all duplicates, triplicates, etc. of commas
This combines the two approaches:
str.replaceAll("382,?", ""); // Remove 382 and an optional comma after it.
Note: both of the last two approaches leave a trailing comma if 382 is at the end.
try this
str = str.replaceAll(",382,", ",");
Firstly, remove the preceding comma in your matching string. Then, remove duplicated commas by replacing commas with a single comma using java regular expression.
String input = "355,356,357,358,359,360,361,382,363,364,365,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,360,361,363,366,368,369,313,370,371,372,373,374,375,376,377,378,379,380,381,382,382,382,382,382,382,383,384,385,380,381,382,382,382,382,382,386,387,388,389,380,381,382,382,382,382,382,382,390,391,380,381,382,382,382,382,382,392,393,394,395,396,397,398,399";
String result = input.replace("382,", ","); // remove the preceding comma
String result2 = result.replaceAll("[,]+", ","); // replace duplicate commas
System.out.println(result2);
As dave already said, the problem is that your pattern overlaps. In the string "...,382,382,..." there are two occurrences of ",382,":
"...,382,382,..."
----- first occurrence
----- second occurrence
These two occurrences overlap at the comma, and thus Java can only replace one of them. When finding occurrences, it does not see yet what you replace the pattern with, and thus it doesn't see that new occurrence of ",382," is generated when replacing the first occurrence is replaced by the comma.
If your data is known not to contain numbers with more than 3 digits, then you might do:
str.replace("382,", "");
and then handle occurrences at the end as a special case. But if your data can contain big numbers, then "...,1382,..." will be replaced by "...,1,..." which probably is not what you want.
Here are two solutions that do not have the above problem:
First, simply repeat the replacement until no changes occur anymore:
String oldString = str;
str = str.replace(",382,", ",");
while (!str.equals(oldString)) {
oldString = str;
str = str.replace(",382,", ",");
}
After that, you will have to handle possible occurrences at the end of the string.
Second, if you have Java 8, you can do a little more work yourself and use Java streams:
str = Arrays.stream(str.split(","))
.filter(s -> !s.equals("382"))
.collect(Collectors.joining(","));
This first splits the string at ",", then filters out all strings which are equal to "382", and then concatenates the remaining strings again with "," in between.
(Both code snippets are untested.)
Traditional way:
String str = ",abc,null,null,0,0,7,8,9,10,11,12,13,14";
String newStr = "", word = "";
for (int i=0; i<str.length(); i++) {
if (str.charAt(i) == ',') {
if (word.equals("null") || word.equals("0"))
word = "";
newStr += word+",";
word = "";
} else {
word += str.charAt(i);
if (i == str.length()-1)
newStr += word;
}
}
System.out.println(newStr);
Output:
,abc,,,,,7,8,9,10,11,12,13,14

removing white spaces from string value

i have a link http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area in my struts based web application.
The variable in URL justificationName have some spaces before its vales as shown. when i get value of justificationName using request.getParameter("justificationName") it gives me that value with spaces as given in the URL. i want to remove those spaces. i tried trim() i tries str = str.replace(" ", ""); but any of them did not removed those spaces. can any one tell some other way to remove the space.
Noted one more thing that i did right click on the link and opened the link into new tab there i noticed that link looks like.
http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName=%A0%A0%A0%A0%A0%A0%A0%A0No%20Technicians%20in%20Area
Notable point is that in the address bar it shows %A0 for white spaces and also show %20 for space as well see the link and tell the difference please if any one have idea about it.
EDIT
Here is my code
String justificationCode = "";
if (request.getParameter("justificationName") != null) {
justificationCode = request.getParameter("justificationName");
}
justificationCode = justificationCode.replace(" ", "");
Note: replace function remove the space from inside the string but not removing starting spaces.
e-g if my string is " This is string" after using replace it becomes " Thisisstring"
Thanks in advance
Strings are immutable in Java, so the method doesn't change the string you pass but returns a new one. You must use the returned value :
str = str.replace(" ", "");
Manual trim
You need to remove the spaces the string. This will remove any number of consecutive spaces.
String trimmed = str.replaceAll(" +", "");
If you want to replace all whitespace characters:
String trimmed = str.replaceAll("\\s+", "");
URL Encoding
You could also use an URLEncoder, which sounds like a more appropriate way to go:
import java.net.UrlEncoder;
String url = "http://localhost:8080/reporting/" + URLEncoder.encode("pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area", "ISO-8859-1");
You have to assign the result of the replace(String regex, String replacement) operation to another variable. See the Javadoc for the replace(String regex, String replacement) method. It returns a brand new String object and this is because the String(s) in Java are immutable. In your case, you can simply do the following
String noSpacesString = str.replace("\\s+", "");
You can use replaceAll("\\s","") It will remove all white space.
If you are trying to remove the trailing and ending white spaces, then
s = s.trim();
Or if you want to remove all the spaces the use :
s = s.replace(" ","");
There are two ways of doing one is regular expression based or your own way of implementing the logic
replaceAll("\\s","")
or
if (text.contains(" ") || text.contains("\t") || text.contains("\r")
|| text.contains("\n"))
{
//code goes here
}

Trim() is not working

while(rs.next()) {
value = rs.getString(1).trim().split(",");
mineral.addAll(Arrays.asList(value));
}
Here the value of rs.getString(1) is given below.
"Dimension Stone, Kankar, River Sand, "
this value is trimed using trim() and split using split(",") and assign to the array value.
Here my problem is trim() do not trim the spaces in the
String.
Can anyone suggest the reason for this and solve my problem?
The trim function does not remove intra-sentence spaces, it only removes the whitespace characters at either end of the string. If you want all the strings trimmed then you need to invoke the function for each one.
String[] values = rs.getString(1).split(",");
for(String value : values) {
mineral.add(value.trim());
}
try to split the string like this
value = rs.getString(1).trim().split(" *, *");
trim() will just remove leading and trailing spaces and not the spaces within the string.
Do you wish to remove space between 'Dimension Stone'?
You have two options to do that, if you wish to use trim() then you can go with Perception answer or you can use replace(""," ")
for example using replace(" ","")
String[] values = rs.getString(1).replace(" ", "").split(",");

Categories