字串基本操作與函式

2021-08-17 08:35:52 字數 2878 閱讀 2196

1)字串型別:

char:定長字串型別,最大長度為2000個位元組。不指定長度時,預設為1個位元組。

varchar2():可變字串長度,最大長度為4000個位元組,必須指定字串長度。

long:varchar2的加長版,最大長度為2g的位元組。

但是在乙個表中,只能存在乙個long型別的字段。

此字段還不能作為主鍵和索引。

clob:可以替代long型別,最大長度為4g的位元組

沒有long型別的限制

預設單位:位元組。

如:char(10),表示占用記憶體10個位元組,相當於char(10bytes)

也可以指定為字元char,如:char(10 char),表示占用記憶體10個字元,

占用位元組數與字符集有關。

2)字串函式:

1.拼接函式:concat(p1,p2)

將字串p1和p2進行無縫連線,可以巢狀

可以使用||來代替拼接函式

--將字串「hello」和「kitty」進行拼接

select concat('hello','kitty') from dual;

select 'hello'||'kitty' from dual;

2.統計長度函式:length(p1);

統計引數p1的字元個數

--統計hellokitty的字元個數

select length('hellokitty') from dual;

--統計'你好,世界'的字元個數

select length('你好,世界') from dual;

3.補位函式

左補位函式:lpad(p1,n,p2)

表示使用p2在p1左邊進行補位,總長度為n(n的單位:位元組)(相當於右對齊)

右補位函式:rpad(p1,n,p2)

表示使用p2在p1右邊進行補位,總長度為n(相當於左對齊)    

--使用'#'在'hello'左邊進行補位,使整個字串達到20位元組長度

select lpad('hello',20,'#') from dual;

--使用'#'在'hello'右邊進行補位,使整個字串達到20位元組長度

select rpad('hello',20,'#') from dual;

4.大小寫函式

lower(p1):將p1中的字元都變成小寫

upper(p1):將p1中的字元都變成大寫

initcap(p1):將p1中的單詞首字母大寫,其餘小寫(空格隔開算乙個字元)

--使用lower函式顯示'no zuo no die'

select lower('no zuo no die') from dual;

--使用upper函式顯示'no zuo no die'

select upper('no zuo no die') from dual;

--使用initcap()顯示'no zuo no die'

select initcap('no zuo no die') from dual;

5.截去函式

trim(p2 from p1):從p1的前後截去p2,p2必須是乙個字元

ltrim(p1,p2):從p1的左邊截去含有p2中任意字元的字元

rtrim(p1,p2):從p1的右邊截去含有p2中任意字元的字元

--截去'上海自來水來自海上'中的'上'

select trim('海' from '上海自來水來自海上') from dual;

--截去'上海自來水來自海上'左邊的'海上來自'

select ltrim('上海自來水來自海上','海上來自') from dual;

--截去'上海自來水來自海上'右邊的'海自上來水'

select rtrim('上海自來水來自海上','海上水來自') from dual;

6.擷取子串函式substr(p1,start,len)

對p1進行擷取,從start位置開始往後擷取。

len引數可以省略,沒有第三個引數時,擷取到 最後;有第三個引數時,都表示從頭擷取。

start為0或者1時,都表示從頭擷取;start為負數時,表示從後往前數第start個。

--擷取'no zuo no die'中的'zuo no'

select substr('no zuo no die',4,6) from dual;

--從倒數第五個位置開始擷取'no zuo no die'

select substr('no zuo no die',-5) from dual;

7.查詢索引函式:instr(p1,p2,m,n)

返回p2在p1的什麼位置,查詢不到返回0

m:可以省略,表示從p1的那個位置開始

n:表示p2的第幾次出現

不寫m,n時,表示從頭開始檢索,第一次出現的位置

寫m,不寫n時,表示從頭開始檢索,第一次出現的位置

--查詢'no zuo no die'中'no'第一次出現的位置

select instr('no zuo no die','no') from dual;

--結果為:1

--查詢'no zuo no die'中'no'第二次出現的位置

select instr('no zuo no die','no',1,2) from dual;

--結果為:8

--查詢'no zuo no die'中'no'從第8位開始檢索,第二次出現的位置

select instr('no zuo no die','no',8,2) from dual;

--結果為:0

基本字串操作函式

strcpy p,p1 複製字串 strncpy p,p1,n 複製指定長度字串 strcat p,p1 附加字串 strncat p,p1,n 附加指定長度字串 strlen p 取字串長度 strcmp p,p1 比較字串 strcasecmp忽略大小寫比較字串 strncmp p,p1,n 比...

字串基本操作

include unsigned int strlenth char s 獲取字串長度 return lenth void strcopy char target,char source 字串拷貝 int strcompare char s,char t 字串比較,s t,則返回1 s t,則返回0...

字串基本操作

遞迴求字串長度 int recurlength char str 字串中最後乙個引數的長度 int lastwordlen char str,int len int lastwordlen char str return lastlen 字串記憶體的拷貝 實現memmove函式 char my me...