DEV Community

Discussion on: Daily Challenge #210 - Separate Capitalization

Collapse
 
dmfay profile image
Dian Fay

SQL:

[local] dian#dian= WITH seq AS (
  SELECT regexp_split_to_table('string', '') AS c
), capitalized AS (
  SELECT
    CASE
      WHEN row_number() OVER () % 2 = 0 THEN upper(c)
      ELSE lower(c)
    END AS even,
    CASE
      WHEN row_number() OVER () % 2 = 1 THEN upper(c)
      ELSE lower(c)
    END AS odd
  FROM seq
)
SELECT
  string_agg(even, '') AS even,
  string_agg(odd, '') AS odd
FROM capitalized;
  even    odd   
────────┼────────
 sTrInG  StRiNg
(1 row)

Time: 0.613 ms

Break the string down into a table with one character per row, use the row_number window function to capitalize it each way, then reassemble the final product; the latter two steps can't be combined because window functions can't be nested in aggregate functions.