Trim() is not working - java

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(",");

Related

How to safely remove the commas on an ArrayList?

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

having trouble with arrays and maybe split

String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}

Replacing Only Certain White Spaces In a String

I have string queryInputNameString that is equal to fir, spotted owl and I'm trying to use replaceAll() to remove the white spaces and split() to separate the elements in the inputNameArray array when a comma occurs.
String noSpaces = queryInputNameString.replaceAll("\\s+","");
String[] inputNameArray = noSpaces.split("\\,");
So far the above returns:
fir
spottedowl
but I would like it to only remove the white spaces that occurs immediately before or after a comma and return this:
fir
spotted owl
How can I make my code ignore white spaces that are not preceded/followed by a comma?
Thanks.
Since split() accepts a regex as argument, you can directly do this:
String[] inputNameArray = queryInputNameString.split("\\s*\\,\\s*");
Otherwise, if you really want to replace only spaces after a comma, you can use:
String noSpaces = queryInputNameString.replaceAll(",\\s+",",");
You actually do not have to use more sophisticated regex. If you just split by comma first and then trim each array element you will get the desired result.
This approach might prove to be less effective when dealing with a lot of data.
String[] inputArray = queryInputNameString.split(",");
for (int i=0; i < inputArray.length, ++i) {
inputArray[i] = inputArray[i].trim();
}

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
}

String manipulation in java using replaceAll()

I have string of the following form:
भन्‍‌ने [-0.4531954191090929, 0.7931147934270654, -0.3875088408737827, -0.09427394940704822, 0.10065554475134718, -0.22044284832864797, 0.3532556916833505, -1.8256229909222224, 0.8036832111904731, 0.3395868096795993]
Whereever [ or ] or , char are present , I just want to remove them and i want each of the word and float separated by a space. It is follows:
भन्‍‌ने -0.4531954191090929 0.7931147934270654 -0.3875088408737827 -0.09427394940704822 0.10065554475134718 -0.22044284832864797 0.3532556916833505 -1.8256229909222224 0.8036832111904731 0.3395868096795993
I am representing each of these string as line. i did following:
line.replaceAll("([|]|,)$", " ");
But it didn't work for me. There was nothing change in the input line. Any help is really appreciated.
Strings are immutable. Try
line = line.replaceAll("([|]|,)$", " ");
Or to be a bit more verbose, but avoiding regular expressions:
char subst = ' ';
line = line.replace('[', subst).replace(']', subst).replace(',', subst);
In Java, strings are immutable, meaning that the contents of a string never change. So, calling
line.replaceAll("([|]|,)$", " ");
won't change the contents of line, but will return a new string. You need to assign the result of the method call to a variable. For instance, if you don't care about the original line, you can write
line = line.replaceAll("([|]|,)$", " ");
to get the effect you originally expected.
[ and ] are special characters in a regular expression. replaceAll is expected a regular expression as its first input, so you have to escape them.
String result = line.replaceAll("[\\[\\],]", " ");
Cannot tell what you were trying to do with your original regex, why you had the $ there etc, would need to understand what you were expecting the things you put there to do.
Try
line = "asdf [foo, bar, baz]".replaceAll("(\\[|\\]|,)", "");
The regex syntax uses [] to define groups like [a-z] so you have to mask them.

Categories