天天看點

matlab字元串處理

一、字元串的構造

字元串構造:寫在單引号之内的内容,如果内容包括單引号,則用重複的單引号來表示

>> str='i''m good'

str =

i'm good           

構造多行字元串:['……';'……']或者{‘……’;‘……’}

前者要求字元串内容長度相同,後者則沒有限制

>> strcat(str,str2)%字元串拼接

ans =

i'm goodright           
>> strvcat(str,str2)

ans =

i'm good
right              

strcat是單行字元串連接配接;strvcat函數和char函數用于縱向連接配接多個字元串。strvcat函數連接配接多行字元串時,每行字元串的長度不要求相等,所有非最長字元串的右端會補空格,使得每行字元串長度相等。

char函數與strvcat函數類似(?)

二、字元串的比較

兩個字元串之間的比較可以通過關系運算符來比較,也可以使用strcmp函數來比較兩個字元串是否相同傳回0或1;

而關系運算符,會對字元串的每個元素進行比較,會傳回一個01數組,且兩字元串長度必須相同

>> sabc=strvcat(a,b,c)

sabc =

top   
      
123456

>> cabc=char(a,b,c)

cabc =

top   
      
123456

>> whos
  Name      Size            Bytes  Class    Attributes

  a         1x3                 6  char               
  ans       3x6                36  char               
  b         1x1                 2  char               
  c         1x6                12  char               
  cabc      3x6                36  char               
  sabc      3x6                36  char               
  str       1x8                16  char               
  str2      1x5                10  char               

>> strcmp(a,b)

ans =

     0

>> sabc==cabc

ans =

     1     1     1     1     1     1
     1     1     1     1     1     1
     1     1     1     1     1     1           

字元串函數:

eval(string):求字元串的值

>> a

a =

top

>> s='a.*2'

s =

a.*2

>> eval(s)

ans =

   232   222   224           

blanks(n):傳回一個n個零或者空格的字元串

deblank:去掉字元串後拖的空格

feval:求字元串給定的函數值

>> f=@(x)x.^2

f = 

    @(x)x.^2

>> x=1:5

x =

     1     2     3     4     5

>> feval(f,x)

ans =

     1     4     9    16    25           

findstr:從一個字元串内部找字元串

isletter:字元存在時傳回真值

isspace:空格字元串存在時傳回真值

isstr:輸入一個字元串傳回真值

lasterr:傳回一個産生matlab'錯誤的字元串

strrep:用一個字元串替換另一個字元串

strtok:在一個字元串裡找出第一個标記

>> strtok(a,';')

ans =

ergfoqejglkfkg           

三、字元串的查找和替換

findstr區分大小寫,對字元串矩陣不起作用

>> str1='hello matlab'

str1 =

hello matlab

>> findstr(str1;'o')
 findstr(str1;'o')
            |
Error: Unbalanced or unexpected parenthesis or bracket.
 
>> findstr(str1,'o')

ans =

     5
           

strrep函數:

直接指派法:替換字元和被替換字元的長度必須一緻

>> str1(1:5)='good'
In an assignment  A(:) = B, the number of elements in A and B
must be the same.
 
>> str1(1:5)='goodd'

str1 =

goodd matlab           

函數法:可以是長度不同的字元串

str1 =

goodd matlab

>> strrep(str1,'goodd','mamai')

ans =

mamai matlab           

三、字元串-數值型轉換

abs:将字元串轉化為asc碼

setstr:asc碼轉換成字元串

>> str='hello matlab'

str =

hello matlab

>> num=abs(str1)

num =

   103   111   111   100   100    32   109    97   116   108    97    98           

fprintf:把格式化的文本寫到檔案中或者顯示屏上 

sprintf:用格式控制數字轉換成字元串

sscanf:按照指定格式讀入

hex2num:十六進制字元串轉換為IEEE浮點數

dec2hex:十進制數轉化為十六進制字元串

int2str:整數轉換成字元串

lower:字元串轉換成小寫     upper字元串轉化為大寫

num2str:數字轉換成字元串

str2mat:字元串轉換成一個文本矩陣

str2num:字元串轉成數字

繼續閱讀