Suppose I have a string 1,2,3,
I would like to remove the last ,
or if the string looks like ,1,2,3,
or ,1,2,3
I would still like to get 1,2,3
as my result.
And please try to be a little explanatory in your answer. I do not just want to copy paste stuff without understanding it. Thank you.
To remove the first and last character of a string, we can use the substring() method by passing 1 as a first argument and string. length()-1 as the second argument in Java. In the example above, the extraction starts from index 1 and ends before the last index (that is string. length()-1 ).
Although the String class doesn't have a remove() method, you can use variations of the replace() method and the substring() method to remove characters from strings.
To remove everything after a specific character in a string:Use the String. split() method to split the string on the character.
With the replaceAll() method, you can use an empty String to remove a substring from a string.
One way to deal with "trimming" commas like that would be using a CASE
statement:
CASE
WHEN str LIKE ',%,' THEN SUBSTRING(str, 2, LEN(str)-2)
WHEN str LIKE ',%' THEN RIGHT(str, LEN(str)-1)
WHEN str LIKE '%,' THEN LEFT(str, LEN(str)-1)
ELSE str
END
This is very much self-explanatory: the CASE
statement considers three situations -
str
has commas on both sides,str
starts in a comma, but does not end in one, andstr
ends in a comma, but does not start in one.In the first case, the first and the last characters are removed; in the second case, the leftmost character is removed; in the last case, the trailing character is removed.
Demo on sqlfiddle.
declare @str varchar(20)=',1,2,3,'
select case
when @str like ',%,' then stuff(stuff(@str, 1, 1, ''),LEN(stuff(@str, 1, 1, '')),1,'')
when @str like ',%' then stuff(@str, 1, 1, '')
when @str like '%,' then stuff(@str, LEN(@str), 1, '')
else @str
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With