首页 > 解决方案 > 从字符串中删除最后两个空格

问题描述

如果我的字符串的长度是 30。我必须从字符串中删除最后 2 个空格。

如果我的字符串的长度是 29。我必须从字符串中删除最后一个空格。

例如。COADC Cathy & Ralph Ward Jr 73应该是COADC Cathy & Ralph WardJr73
而不是COADCCathy&RalphWardJr73

尝试了, 和trim()空格instr但没有成功。还有其他功能吗?substrreplace()

标签: sqloraclereplace

解决方案


我会为此目的创建一个函数:

create function reducestr
    (str in varchar2,
     len in number,
     sp in varchar2 := ' '
    ) return varchar2 is
    pos number;
    buf varchar2(4000);
begin
    buf := trim(sp from str);
    loop
        if length(buf) <= len then
            -- great, we're already at or under the target length
            return buf;
        else
            -- find the position of the last occurrence of a space
            pos := instr(buf, sp, -1);
            if pos = 0 then
                -- no more spaces to remove, just truncate the string
                return substr(buf, 1, len);
            else
                -- remove the last space
                buf := substr(buf, 1, pos-1) || substr(buf, pos+1);
            end if;
        end if;
    end loop;
end reducestr;

select reducestr('COADC Cathy & Ralph Ward Jr 73',28) from dual;

COADC Cathy & Ralph WardJr73

推荐阅读