如何顯示一個字串,用一個帶有 for 回圈的破折號分隔每個字母?
例如我想顯示:
你好世界
我嘗試使用substr函式,但無法將其取出
uj5u.com熱心網友回復:
如果它必須是 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>
uj5u.com熱心網友回復:
您可以只輸出每個連續的字符,并在第一個字符之后輸出它們之間的連字符:
DECLARE
string VARCHAR2(20) := 'helloworld';
BEGIN
DBMS_OUTPUT.PUT(SUBSTR(string, 1, 1));
FOR i IN 2 .. LENGTH(string)
LOOP
DBMS_OUTPUT.PUT('-');
DBMS_OUTPUT.PUT(SUBSTR(string, i, 1));
END LOOP;
DBMS_OUTPUT.NEW_LINE();
END;
/
哪個輸出:
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) );
END;
/
您不應使用LTRIM(或RTRIM) 洗掉連字符,因為如果輸入字串具有前導(或尾隨)連字符,則這些連字符將從輸出中洗掉,這是錯誤的。
例如:
DECLARE
string VARCHAR2(20) := '--helloworld--';
BEGIN
DBMS_OUTPUT.PUT_LINE('Correct:');
DBMS_OUTPUT.PUT_LINE(SUBSTR(REGEXP_REPLACE(string, '(.)', '-\1'), 2));
DBMS_OUTPUT.PUT_LINE('Incorrect:');
DBMS_OUTPUT.PUT_LINE(LTRIM(REGEXP_REPLACE(string, '(.)', '-\1'), '-'));
END;
/
輸出:
Correct: ----h-e-l-l-o-w-o-r-l-d---- Incorrect: h-e-l-l-o-w-o-r-l-d----
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472555.html
