Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a specific character from a string, only when it is the first or last character in the string.

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.

like image 826
SamuraiJack Avatar asked Dec 20 '13 05:12

SamuraiJack


People also ask

How do you get the first and last character of a string How do you remove the first and last character of a string?

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 ).

How do I remove a character from the beginning and end of a string?

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.

How do I remove all characters from a string after a specific character?

To remove everything after a specific character in a string:Use the String. split() method to split the string on the character.

How do I remove a specific part of a string?

With the replaceAll() method, you can use an empty String to remove a substring from a string.


2 Answers

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 -

  • When the string str has commas on both sides,
  • When the string str starts in a comma, but does not end in one, and
  • When the string str 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.

like image 163
Sergey Kalinichenko Avatar answered Oct 22 '22 20:10

Sergey Kalinichenko


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
like image 41
Poonam Avatar answered Oct 22 '22 22:10

Poonam