我有一个字符串。让我们说:“abcdea” 我必须找出使用匿名pl / sql块的字符串中最常用的字母。
我该怎么做?
答案 0 :(得分:2)
也许不是很优雅,但仍在工作:
declare
str varchar2(6 char) := 'abcdea';
alphabet varchar2(26 char) := 'abcdefghijklmnopqrstuvwxyz';
most_frequent char := '';
max_count INTEGER := 0;
v_count INTEGER := 0;
checking CHAR := '';
begin
for i in 1..26 loop
checking := SUBSTR(alphabet, i, 1);
for k in 1..length(str)
loop
if SUBSTR(str, k, 1) = checking THEN
v_count := v_count + 1;
end if;
end loop;
if v_count > max_count THEN
max_count := v_count;
most_frequent := checking;
end if;
v_count :=0;
end loop;
dbms_output.put_line('Most frequent letter is "'|| most_frequent||'"');
end;
答案 1 :(得分:2)
关联数组非常便于存储计数:
DECLARE
TYPE t_counts IS TABLE OF PLS_INTEGER INDEX BY VARCHAR2(1);
--
v_counts t_counts;
v_string VARCHAR2(100) := 'the quick brown fox jumped over the lazy dog';
v_char VARCHAR2(1);
BEGIN
FOR i IN 1 .. length( v_string ) LOOP
v_char := substr( v_string, i, 1 );
IF NOT v_counts.exists( v_char ) THEN
v_counts( v_char ) := 0;
END IF;
v_counts( v_char ) := v_counts( v_char ) + 1;
END LOOP;
END;
/
在数组中查找具有最高计数的索引将是微不足道的添加
答案 2 :(得分:0)
创建表
create table charcount ( c char(1) )
将字符串拆分为单个字符,并使用PL / SQL将它们插入此表中。答案就是第一行:
select c, count(1)
from charcount
group by c
order by count(1) desc
答案 3 :(得分:0)
以下是使用几种SYS类型的解决方案:
declare
str varchar2(6) := 'abcdea';
tab AWRDRPT_TEXT_TYPE_TABLE := AWRDRPT_TEXT_TYPE_TABLE();
begin
for i in 1..length(str) loop
tab.extend(1);
tab(i) := AWRDRPT_TEXT_TYPE (substr(str,i,1));
end loop;
for r in (select output, count(*) as cnt
from table(tab)
group by output
order by cnt desc)
loop
dbms_output.put_line(r.output);
exit;
end loop;
end;
答案 4 :(得分:0)
在纯SQL上没有PL / SQL就可以了
declare
l_string varchar2(1000) := 'asddafsbaterbtretbbfdsbgdfsgnrtynrthfhfghntumfyuy';
l_char char(1);
begin
with t as
(select l_string as str from dual)
select c
into l_char
from (select substr(str, level, 1) as c, count(*) as cnt
from t
connect by level <= length(str)
group by substr(str, level, 1)
order by 2 desc)
where rownum < 2;
dbms_output.put_line('Most used char is ' || l_char);
exception
when no_data_found then
dbms_output.put_line('Sorry string is empty');
end;