> x1<-c("my","name","is");x2<-c("sophia");
> x1;x2
[1] "my" "name" "is"
[1] "sophia"
1.连接两个字符串:
> newc<-c(x1,x2)
> newc
[1] "my" "name" "is" "sophia"
> nchar<-paste(x1,"something",x2,sep=":")
> nchar
[1] "my:something:sophia" "name:something:sophia" "is:something:sophia"
2,取其中一段字符串:substr(字符串,起始位置,结束位置)
substr(x1,2,3) [1] "y" "am" "s"
3.计算字符串的长度:nchar(字符串)
> nchar(x1);nchar(x2)
[1] 2 4 2
[1] 6
4.在字符串中查找变量:
grep(变量,字符串):返回变量在字符串中所在的位置
regexpr(变量,字符串):返回变量在字符串中的所有位置
> grep("y",x1);grep("nam",x2);grep("nam",x1) [1] 1 integer(0) [1] 2
> regexpr("nam",x1) [1] -1 1 -1 attr(,"match.length") [1] -1 3 -1 attr(,"useBytes") [1] TRUE
5.查找近似的字符串:
> agrep("favor","I ask a favor"); [1] 1
6.替换字符串:
gsub(要替换的字符串,新字符串,整个字符串)
> x="oldpat123";x [1] "oldpat123" > substr(x,2,5)="new" > x [1] "onewat123"
> gsub("ldp","new",x) [1] "onewat123"
7.转换成小写:tolower(字符串)
> tolower("ABC") [1] "abc"