![]() |
没有腹肌的鞭炮 · “你投资做得这么好,居然是东北的?”丨Cit ...· 9 月前 · |
![]() |
兴奋的冲锋衣 · 关于雷神"三千烈士"事件 ...· 1 年前 · |
![]() |
酷酷的水煮鱼 · 浙江省举行农业机械化发展情况新闻发布会· 1 年前 · |
![]() |
善良的凉面 · 养猫好还是养狗好,养猫的好处和坏处- 知乎· 1 年前 · |
![]() |
逼格高的蜡烛 · 热火总裁莱利因违规招募詹姆斯,被联盟罚款!引 ...· 1 年前 · |
如何显示字符串,用for循环用破折号分隔每个字母?
例如,我想显示:
h-e-l-l-o-w-o-r-l-d
我试过使用 substr 函数,但我无法把它拿出来
发布于 2022-05-09 09:29:47
如果它必须是PL/SQL和
FOR
循环,那么可以
SQL> set serveroutput on
SQL> declare
2 l_str varchar2(20) := 'helloworld';
3 retval varchar2(50);
4 begin
5 for i in 1 .. length(l_str) loop
6 retval := retval || substr(l_str, i, 1) ||'-';
7 end loop;
8 retval := rtrim(retval, '-');
9 dbms_output.put_line(retval);
10 end;
11 /
h-e-l-l-o-w-o-r-l-d
PL/SQL procedure successfully completed.
SQL>
否则,考虑一下。
SQL> select rtrim(regexp_replace('helloworld', '(.)', '\1-'), '-') result from dual;
RESULT
-------------------
h-e-l-l-o-w-o-r-l-d
SQL>
或
SQL> select listagg(substr('helloworld', level, 1), '-') within group (order by level) result
2 from dual
3 connect by level <= length('helloworld');
RESULT
--------------------------------------------------------------------------------
h-e-l-l-o-w-o-r-l-d
SQL>
发布于 2022-05-09 09:48:54
您只需输出每个连续字符,并且在第一个字符之后,在它们之间输出一个连字符:
DECLARE
string VARCHAR2(20) := 'helloworld';
BEGIN
DBMS_OUTPUT.PUT(SUBSTR(string, 1, 1));
FOR i IN 2 .. LENGTH(string)
DBMS_OUTPUT.PUT('-');
DBMS_OUTPUT.PUT(SUBSTR(string, i, 1));
END LOOP;
DBMS_OUTPUT.NEW_LINE();
/
其中产出:
h-e-l-l-o-w-o-r-l-d
如果您想不使用循环,那么可以使用:
DECLARE
string VARCHAR2(20) := 'helloworld';
BEGIN
DBMS_OUTPUT.PUT_LINE( SUBSTR(REGEXP_REPLACE(string, '(.)', '-\1'), 2) );
/
您不应该使用
LTRIM
(或
RTRIM
)删除连字符,因为如果输入字符串有前导(或尾随)连字符,那么这些字符将从输出中删除,这将是错误的。
例如:
DECLARE
string VARCHAR2(20) := '--helloworld--';
BEGIN