MATLAB 程式設計/字串
字串使用單引號 ( ' ) 宣告
>> fstring = 'hello'
fstring =
hello
在字串中包含單引號需要這樣做
>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're
在 MATLAB 中,可以使用方括號將多個字串連線(連線在一起形成一個鏈)。
<concatstring>=[<str1>,<str2>,<str3>,...];
以下是使用此連線函式的隨機問候語訊息。
>> subject='The quick brown fox ' %sentence beginning
subject =
'The quick brown fox '
>> verb = 'jumps over '
verb =
'jumps over '
>> object='the lazy dog'
object =
'the lazy dog'
>> phrase=[subject,verb,object]
phrase =
'The quick brown fox jumps over the lazy dog'
為了讓使用者輸入,我們可以使用input函式
>> name=input('Enter your names: ','s')
Enter your names: Matlab_User
name =
'Matlab_User'

考慮以下繞口令
一隻土撥鼠能扔多少木頭
如果土撥鼠能扔木頭?
他會扔,他會,盡他所能,
並且扔的木頭和土撥鼠一樣多
如果土撥鼠能扔木頭。
我們想知道單詞wood在這個繞口令中出現了多少次。我們可以使用count函式。
>>%Declare woodchuck twister as an characther vectors
>> twister = 'How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.'
twister =
'How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.'
>> count(twister,"wood")
ans =
8

請注意,count函式統計字串中模式的出現次數。
因此,它將在單詞“woodchuck”中統計單詞“wood”的出現次數。
現在,我們有另一個示例來統計所有時間中最著名的諺語中“the”這個單詞的出現次數。
狡猾的棕色狐狸跳過懶惰的狗
phrase = 'The quick brown fox jumps over the lazy dog'
%count function is case-sensitive by default . It did not count The with capital 'T'
>> count(phrase,'the')
ans =
1
%need to use IgnoreCase to turn off the case-sensitive words
>> count(phrase,'the','IgnoreCase',true)
ans =
2
有時,您可能需要查詢句子中單詞的長度,這裡length(string')函式可以為您提供幫助。
>> length(phrase)
ans =
43
正如我們在下一節中看到的,可以看出字串中正好有 43 個字元。
要從字串中提取特定單詞,需要stringName(indexnumberfirst:indexnumberlast)。
我們使用與上面相同的示例短語。
請注意,即使是空格也被視為字串。
| 索引號 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |
| 字串 | T | h | e | q | u | i | c | k | b | r | o | w | n | f | o | x | j | u | m | p | s | o | vv | e | r | t | h | e | l | a | z | y | d | o | g |
根據此示例,如果我們想提取單詞brown fox和lazy dog,
我們可以看到每個單詞分別由索引號 (11:19) 和索引號 (36:43) 表示。在 MATLAB 中,我們可以鍵入以下命令
>> phrase(11:19)
ans =
'brown fox'
>> phrase(36:43)
ans =
'lazy dog'
對於字串操作,例如將字串轉換為大小寫,我們可以使用lower和upper函式。這將使字串分別全部變為小寫和 大寫字元。
>> upper(phrase)
>> %Convert the string to uppercase
ans =
'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
>> lower(phrase)
>> %Convert the string to lowercase
ans =
'the quick brown fox jumps over the lazy dog'
要反轉字串,我們可以使用reverse/flip函式。這將使字串從最後一個索引號反轉到第一個索引號,反之亦然。
>> reverse(phrase)
ans =
'god yzal eht revo spmuj xof nworb kciuq ehT'
要替換字串中的特定單詞,我們可以使用replace函式
replace 函式的語法如下:replace(stringName,oldword,newword)
>>% We don't want brown fox, we want to change to orange fox
>> replace(phrase,'brown','orange')
ans =
'The quick orange fox jumps over the lazy dog'
有時,您可能希望一次替換多個單詞,因此我們需要在向量中宣告多個字串。但在此之前,請確保舊單詞和新單詞的順序/序列是正確的。
>>%declare vector where the old words are going to be replaced
>> old={'fox','dog'}
old =
1×2 cell array
{'fox'} {'dog'}
>>%declare vector where the new words are going to do the replaing
>> new={'cheetah','sloth'}
new =
1×2 cell array
{'cheetah'} {'sloth'}
>> % Replace old words (fox) and (dog) into (cheetah) and (sloth) . Make sure sequence is in correct order
>> replace(phrase,old,new)
ans =
'The quick brown cheetah jumps over the lazy sloth'
MATLAB 中的字串是字元陣列。要檢視這一點,請執行以下程式碼
>> fstring = 'hello';
>> class(fstring)
ans = char
因為字串是陣列,所以許多陣列操作函式都可用,包括:size、transpose 等。可以對字串進行索引以訪問特定元素。
對字元陣列執行算術運算會將其轉換為雙精度浮點數。
>> fstring2 = 'world';
>> fstring + fstring2
ans = 223 212 222 216 211
這些數字來自陣列中每個字元的 ASCII 標準。這些值是使用double 函式獲得的,該函式將陣列轉換為雙精度浮點數陣列。
>> double(fstring)
ans = 104 101 108 108 111
‘char’ 函式可以將雙精度浮點數的整數陣列轉換回字元。嘗試將小數轉換為字元會導致 MATLAB 向下取整。
>> char(104)
ans = h
>> char(104.6)
ans = h
由於 MATLAB 字串是字元陣列,因此可以使用一些特殊函式來比較整個字串,而不僅僅是其元件。
deblank 從字串中刪除空格。
findstr(bigstring, smallstring) 檢視較小的字串是否包含在較大的字串中,如果包含,則返回較小的字串開始位置的索引。否則,它將返回 []。
strrep(string1, replaced, replacement) 將string1 中所有出現的replaced 替換為replacement。
與有理陣列不同,字串不能使用關係運算符進行正確比較。要比較字串,請使用strcmp 函式,如下所示
>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0
請注意,MATLAB 字串區分大小寫,因此 ‘a’ 和 ‘A’ 不相同。此外,strcmp 函式不會丟棄空格
>> strcmp(string1, ' a')
ans = 0
字串在各方面必須完全相同。
如果輸入是數字陣列,則 strcmp 函式將返回 0,即使值相同。因此,它僅適用於字串。對於數字值,請使用 == 運算子。
>> strcmp(1,1)
ans = 0.
將數字轉換為字元。此函式在您要使用函式disp 值來限制小數點顯示時非常有用。
>>%Limit the display of pi value to 9 decimal points
>> num2str(pi,'%1.9f')
ans =
'3.141592654'
如果您只想顯示字串的值,則可以省略分號,這在 MATLAB 中是標準的。
如果您想在命令視窗中與其他文字組合顯示字串,一種方法是使用陣列表示法以及 ‘display’ 或 ‘disp’ 函式
>> fstring = 'hello';
>> display( [ fstring 'world'] )
helloworld
MATLAB 不會在兩個字串之間新增空格。如果需要新增空格,則必須手動新增。
此語法也用於將兩個或多個字串連線成一個變數,這允許在字串中插入不尋常的字元
>> fstring = ['you' char(39) 're']
fstring = you're
任何其他返回字串的函式也可以在陣列中使用。
您還可以使用 "strcat" 函式連線字串,當使用兩個字串時,該函式與上述方法相同,但當使用字串元胞陣列時它特別有用,因為它允許您將同一內容連線到所有字串中一次。不幸的是,您不能使用它來新增空格(strcat 會丟棄 MATLAB 認為是多餘的空格)。以下是此用途的語法。
>> strCell = {'A', 'B'};
>> strcat(strCell, '_');
ans =
A_
B_
最後,雖然 MATLAB 沒有 printf 函式,但您可以透過在fprintf 函式中使用1 作為檔案識別符號來實現基本相同的功能。格式識別符號與 C 中基本相同。
>> X = 9.2
>> fprintf(1, '%1.3f\n', X);
9.200
"9.200" 被列印到螢幕上。與 display 相比,fprintf 很棒,因為您不必對字串中的所有數字呼叫 num2str - 只需在需要的位置使用適當的格式識別符號即可。
>> X = 9.2
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second
在許多應用程式中(特別是那些解析文字檔案、讀取帶文字的 Excel 表格等的應用程式),您會遇到字串元胞陣列。
您可以使用 "iscellstr" 函式來判斷給定元胞陣列中的所有元素是否都是字串。
>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0
這很有用,因為處理字串元胞陣列的函式如果提供非字串元胞陣列,則會失敗。特別是,如果提供的文字檔案包含空單元格,它們都會失敗,如果提供的元胞陣列的任何元素都是空陣列([]),這有點令人沮喪。您必須在呼叫 cellstr 操作函式之前捕獲此異常。
可以使用 "strmatch"、"strfind" 和 "regexp" 函式搜尋字串元胞陣列。Strmatch 在字串元胞陣列中查詢其第一個字元與傳遞給它的字串完全匹配的字串,並返回陣列中找到匹配項的所有字串的索引。如果您給出 ‘exact’ 選項,它只會返回與傳遞給它的字串完全相同的元素的索引。例如
>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell);
ans = 1, 2
>> strmatch('A', strCell, 'exact');
ans = []
>> strmatch('Aa', strCell, 'exact');
ans = 1
Strfind 在字串元胞陣列中查詢特定字串,但它嘗試在每個字串的任何部分查詢它。對於給定字串元胞陣列的每個元素 x,如果在 x 中沒有找到匹配項,則它將返回一個空陣列,如果找到了對查詢的匹配項,則返回 x 中所有匹配項的起始索引(記住,字串是字元陣列)。
>> strCell = {'Aa', 'AA'};
>> strfind(strCell, 'A');
ans = % answer is a cell array with two elements (same size as strCell):
1 % Index of the beginning of string "A" in the first cell
1 2 % Index of each instance of the beginning of string "A" in the second cell
>> strfind(strCell, 'a');
ans =
2
[] % 'a' is not found
"cellfun" / "isempty" 組合對於識別字符串是否找到非常有用。您可以將 find 函式與這兩個函式結合使用以返回找到查詢字串的所有單元格的索引。
>> strCell = {'Aa', 'AA'};
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell); % Returns "0" if idxCell is empty and a "1" otherwise
>> foundIdx = find(isFound)
foundIdx = 2
strfind 函式還有一些其他選項,例如僅返回第一個或最後一個匹配項的索引的選項。有關詳細資訊,請參閱文件。
regexp 函式的工作方式與 strfind 相同,但它不是直接查詢字串,而是使用正則表示式嘗試在字串元胞陣列中查詢匹配項。正則表示式是查詢字串中模式(不僅僅是字串中的特定字串)的強大方法。已經出版了許多關於正則表示式的書籍,因此在這裡無法詳細介紹。但是,一些好的線上資源包括 regular-expresions.info 和 MATLAB 文件中關於 MATLAB 特定語法的部分。請注意,MATLAB 實現了一些(但並非所有)其他語言(如 Perl)中可用的擴充套件正則表示式。
不幸的是,MATLAB 本身沒有函式來執行其他一些語言中常見的字串操作,例如字串分割。但是,在 Google 搜尋中很容易找到其中許多函式。