tags:

views:

214

answers:

2

Here is the table data with the column name as Ships.

+--------------+
Ships          |
+--------------+
Duke of north  |
---------------+
Prince of Wales|
---------------+
Baltic         |
---------------+

Replace all characters between the first and the last spaces (excluding these spaces) by symbols of an asterisk (*). The number of asterisks must be equal to number of replaced characters.

A: 

This really smells like homework. So I won't provide you with the full deal, but point you in the right direction instead:

Check out the function InStr. Espcecially its 3rd and 4th parameters, that allow you to search starting at the Xth char and/or search the Yth occurrence.

Edit: If someone finds this thread in a search and hopes for a solution that works in older versions of Oracle, this is how I'd have done it. (I posted it as a comment to another post, but the author deleted his answer for some inexplicable reason o_O )

SELECT case
         when InStr(Name, ' ', 1) > 0 and
              InStr(Name, ' ', 1) <> InStr(Name, ' ', -1) then
           SubStr(Name, 1, InStr(Name, ' ', 1) - 1) ||
           lPad('*', InStr(Name, ' ', -1) - InStr(Name, ' ', 1) + 1, '*') ||
           SubStr(Name, InStr(Name, ' ', -1) + 1)
         else
           Trim(Name)
       end
FROM   SomeTable
Robert Giesecke
Hey man its not an HW question, it was a tricky question which I tried for one whole day but still I am yet to find answer. I never post a question in stack overflow, before trying to to solve it for ample number of times.
+2  A: 

Regular expressions are your friend :)

First match the space, followed by any other characters, ending in a space. Then replace that with a string that consists of the starting and trailing space and, in between, a string of asterisks.

The string of asterisks is made by right padding a single asterisk with further asterisks to the appropriate length. That length is the length of the regular expression matched minus two characters for the leading/trailing space.

select regexp_replace(column_value,' .* ', 
          ' '||rpad('*',length(regexp_substr(column_value,' .* '))-2,'*')||' ')
from table(sys.dbms_debug_vc2coll(
       'Duke of north','Prince of Wales','Baltic','what if two spaces'));

Duke ** north
Prince ** Wales
Baltic
what ****** spaces
Gary