检查字符串是否以另一个字符串开头最方便的方法是什么?

时间:2021-07-09 01:37:54

I would like to have a proper way to check whether a string is the beginning of another string (and that they are not the same).

我想有一个正确的方法来检查字符串是否是另一个字符串的开头(并且它们不相同)。

Given s1 and s2 I have the following possibilities:

给定s1和s2我有以下可能性:

LENGTH(s1) < LENGTH(s2) AND SUBSTR(s2, 1, LENGTH(s1)) = s1

s2 LIKE replace(replace(replace(s1,'\','\\'),'%','\%'),'_','\_') || '_%' ESCAPE '\'

Is there a better way with native functions I don't know of?

有没有更好的方法与我不知道的本机功能?

Note: s1 and s2 might contain %, _ or any other characters!

注意:s1和s2可能包含%,_或任何其他字符!

Thanks.

2 个解决方案

#1


2  

I don't think it is a better way, but for completeness there is also:

我不认为这是一种更好的方式,但为了完整性,还有:

LENGTH(s1) < LENGTH(s2) AND INSTR(s2,s1) = 1

#2


0  

Just a simple if statement should do it:

只需一个简单的if语句即可:

set serveroutput on

declare
  s1 varchar2(1000) := 'hellothere';
  s2 varchar2(1000) := 'hello';
begin
  if s1 != s2 and s1 like s2||'%' then
    dbms_output.put_line('There are alike');
  else
    dbms_output.put_line('not alike');
  end if;
end;

#1


2  

I don't think it is a better way, but for completeness there is also:

我不认为这是一种更好的方式,但为了完整性,还有:

LENGTH(s1) < LENGTH(s2) AND INSTR(s2,s1) = 1

#2


0  

Just a simple if statement should do it:

只需一个简单的if语句即可:

set serveroutput on

declare
  s1 varchar2(1000) := 'hellothere';
  s2 varchar2(1000) := 'hello';
begin
  if s1 != s2 and s1 like s2||'%' then
    dbms_output.put_line('There are alike');
  else
    dbms_output.put_line('not alike');
  end if;
end;