Substr()函数

Substr Function

Oracle/PLSQL: Substr Function


In Oracle/PLSQL, the substr functions allows you to extract a substring from a string.

The syntax for the substr function is:

substr( string, start_position, [ length ] )

string is the source string.

start_position is the position for extraction. The first position in the string is always 1.

length is optional. It is the number of characters to extract. If this parameter is omitted, substr will return the entire string.

Note:

If start_position is 0, then substr treats start_position as 1 (ie: the first position in the string).

If start_position is a positive number, then substr starts from the beginning of the string.

If start_position is a negative number, then substr starts from the end of the string and counts backwards.

If length is a negative number, then substr will return a NULL value.

For example:

substr('This is a test', 6, 2)would return 'is'
substr('This is a test', 6)would return 'is a test'
substr('TechOnTheNet', 1, 4)would return 'Tech'
substr('TechOnTheNet', -3, 3)would return 'Net'
substr('TechOnTheNet', -6, 3)would return 'The'
substr('TechOnTheNet', -8, 2)

would return 'On'

PL/SQL BOOCK:

variable g_char varchar2(30);

variable g_num number;

declare

v_char varchar2(30);

v_num number;

begin

   v_char := '42 is answer';

   :g_char := v_char;

   :g_num := substr(V_CHAR,1,2);

end;

/

print g_char;

print g_num;

SUBSTR 函数用于从字符串中提取子字符串,不同环境下该函数的使用方式略有不同,下面分别介绍其在 Oracle 和 C++ 中的使用方法。 在 Oracle 中,SUBSTR 函数的基本语法为 `SUBSTR(string, start_position, length)`。其中,`string` 是要进行截取的字符串,`start_position` 是开始截取的位置,若为正数则从字符串开头开始计数,若为负数则从字符串末尾开始计数,`length` 是要截取的字符数量。示例如下: ```sql -- 截取从第 1 个字符开始的 3 个字符 SELECT SUBSTR('HelloWorld', 1, 3) FROM DUAL; -- 返回结果:Hel -- 截取从第 2 个字符开始的 3 个字符 SELECT SUBSTR('HelloWorld', 2, 3) FROM DUAL; -- 返回结果:ell -- 从后面倒数第 3 位开始往后取 3 个字符 SELECT SUBSTR('HelloWorld', -3, 3) FROM DUAL; -- 返回结果:rld ``` 当 `length` 超出字符串的最大长度时,系统按字符串的最大数量返回;若 `start_position` 为负数且截取长度超出范围,会按实际可截取的字符返回[^1]。 在 C++ 中,`substr` 是 `std::string` 类的成员函数,其语法为 `s.substr(pos, len)`,从初始位置 `pos` 开始读取长度为 `len` 个字符。示例代码如下: ```cpp #include <iostream> #include <string> int main() { std::string s = "12345 abc"; // 从第 0 个位置开始截取 5 个字符 std::cout << s.substr(0, 5) << std::endl; // 从第 0 个位置开始截取 7 个字符 std::cout << s.substr(0, 7) << std::endl; // 从第 6 个位置开始截取 4 个字符 std::cout << s.substr(6, 4) << std::endl; // 当 pos+len-1 超过字符串的范围时,自动调整 len 的长度从而复制到字符串 s 的最后一个字符 std::cout << s.substr(6, 9) << std::endl; // 当 pos 超过字符串的范围时,substr 函数会抛出一个 out_of_range 的异常 // std::cout << s.substr(11, 1) << std::endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值