對字串進行操作

2021-09-27 03:30:35 字數 2319 閱讀 1570

建立字串是通過一對雙引號「」或使用函式as.character()來完成的。

> string<-c("one","two","three")

> string

[1] "one" "two" "three"

> as.character(1:3)

[1] "1" "2" "3"

函式noquote()可用來抑制r的輸出結果中雙引號的顯示。

> noquote(string)

[1] one two three

函式squote()和dquote用來顯示不同樣式的引號

> squote(string)

[1] "『one』" "『two』" "『three』"

> dquote(string)

[1] "「one」" "「two」" "「three」"

函式nchar()計算乙個字串中字元的數目,它可對乙個字串向量進行操作

> string1<-c("a","ab","b","bba","one","!@","brute")

> nchar(string1)

[1] 1 2 1 3 3 2 5

> string1[nchar(string1)>2]

[1] "bba" "one" "brute"

命令letters和letters分別返回26個小寫和大寫的拉丁字母

> letters

[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"

[19] "s" "t" "u" "v" "w" "x" "y" "z"

> letters

[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"

[19] "s" "t" "u" "v" "w" "x" "y" "z"

函式paste()用於連線若干個字串。

> string2<-c("e","d")

> paste(string1,string2)

[1] "a e" "ab d" "b e" "bba d" "one e" "!@ d" "brute e"

> paste(string1,string2,sep="-")

[1] "a-e" "ab-d" "b-e" "bba-d" "one-e" "!@-d" "brute-e"

> paste(string1,string2,collapse = "",sep="")##collapse可用來實現將字串向量中的元素連線成 單個字串

[1] "aeabdbebbadonee!@dbrutee"

函式strstring()用來從乙個字串中提取子字串

> substring("abcdef",first=1:3,last=2:4)

[1] "ab" "bc" "cd"

> ?substring

> substring("abcdef",first=1,last=5)

[1] "abcde"

函式strsplit()用於**乙個字串

> strsplit(c("05 jan","06 feb"),split=" ")

[[1]]

[1] "05" "jan"

[[2]]

[1] "06" "feb"

函式grep()用來在字串向量中搜尋某一種模式,他返回字串向量中包含這一模式的元素的位置索引。

> grep("i",c("pierre","benoit","rems"))

[1] 1 2

函式gsub()將字串向量中所有元素中具有某一模式的部分以另外乙個字元(串)進行替換。

> gsub("i","l",c("pierre","benoit","rems"))

[1] "plerre" "benolt" "rems"

函式sub()僅替換第乙個具有特定模式的字串中的那一部分。

> sub("r","l",c("pierre","benoit","rems"))

[1] "pielre" "benoit" "lems"

函式tolower()和toupper()可分別用來將乙個字串強制變為小寫或大寫形式。

> tolower("lower")

[1] "lower"

> toupper("upper")

[1] "upper"

對字串進行排序

給三個字串,對它們進行排序,之前寫過對三個數排序,定義乙個中間變數,a,b,c依次比較,如果不是順序,就用臨時變數對它們進行交換。字串也可以用這樣的方法進行排序。void sort const char a,const char b,const char c 字串不能被修改,應該用const修飾 i...

利用 對字串進行相關操作

首部子串替換與尾部子串替換 分別使用 鍵盤上兩個鄰居,作為首部替換,作為尾部替換。形象記憶,無它 bigorry cti2 echo 首部檢驗,成功 bigorry bigorry cti2 echo 非首部,失敗 bigorry bigorry cti2 echo 普通的子串替換,成功 bigor...

SQL對字串進行排序

假設字串中只由 a b c d 組成,且長度為7。並設函式replicate 字串 可以建立乙個 字串 的n個副本的字串,另外還有replace 目標字串 老字串 新字串 實現如下 begin declare instring char 7 set instring dcdbaab replicat...