2016-03-22 30 views
1

我想解決其他編程語言中的一個簡單問題,但我無法在PL/SQL上處理它。我必須提及,我是PL/SQL的初學者。如何計算在PL/SQL中有多少單詞有給定的字母

問題聽起來像這樣:我有一個字符串與許多單詞用空格分隔,我必須計算有多少單詞在他們的組成中有字母「u」。

我對這個問題做了些什麼,但不是我在找什麼。在我的代碼中,我計算了所有字符串中有多少「u」。有任何想法嗎?謝謝。

set serveroutput on; 
DECLARE 
    v_sir VARCHAR2(225) := 'grass car unity united car until'; 
    v_I NUMBER := 1; 
    v_count NUMBER := 0; 
BEGIN 
    WHILE v_I <= LENGTH(v_sir) 
    LOOP 
     IF substr(v_sir, v_I, 1) IN ('u', 'U') THEN 
      v_count := v_count + 1; 
     END IF; 
     v_I := v_I + 1; 
    END LOOP; 
dbms_output.put_line('The number of "u" is: ' || v_count); 
END; 

回答

3
SET SERVEROUTPUT ON; 
DECLARE 
    v_sir VARCHAR2(225) := 'grass car unity united car until unusual'; 
    v_count NUMBER  := REGEXP_COUNT(v_sir, '\S*u\S*'); 
BEGIN 
    dbms_output.put_line('The number of words containing "u" is: ' || v_count); 
END; 
/

輸出4

+0

我喜歡O(1)方法。我正準備將我的答案作爲SQL發佈,以空格作爲分隔符來分割字符串,然後'INSTR'檢查'u',然後檢查'COUNT(*)'。但我認爲這與此無關。 – ruudvan

0

正則表達式的方法很簡單,並且不需要任何PL/SQL的話 - 你可以只從簡單的SQL調用它。但是,如果你將此作爲練習,並且真的想要這樣做,那麼可以使用硬蠻力的方式來循環查找字符串中的字符,查找空格(或者任何其他空白字符,如果需要)查找字邊界,並且只能算「U在話你還沒有見過的外觀:

set serveroutput on; 
declare 
    v_sir varchar2(225) := 'grass car unity united car until unused nu'; 
    v_word_has_u boolean := false; 
    v_count number := 0; 
begin 
    for v_i in 1..length(v_sir) loop 
    if substr(v_sir, v_i, 1) = ' ' then 
     -- new word; can look for other whitespace characters too 
     -- reset flag so we start looking for 'u's again 
     v_word_has_u := false; 
    elsif v_word_has_u then 
     -- already counted this word 
     continue; 
    elsif substr(v_sir, v_i, 1) in ('u', 'U') then 
     -- first u/U in the word we're looking at, so incremment counter 
     v_count := v_count + 1; 
     -- set flag so we don't count any more from this word 
     v_word_has_u := true; 
    end if; 
    end loop; 
    dbms_output.put_line('The number of words with "u" is: ' || v_count); 
end; 
/

PL/SQL procedure successfully completed. 

The number of words with "u" is: 5 

但是,這純粹是作爲一個練習,沒有理由在現實世界中做這樣的事時有內置在功能上你可以使用。

相關問題