在 MATLAB 中連線字串

Ammar Ali 2022年5月11日
在 MATLAB 中連線字串

本教程將討論使用 Matlab 中的函式 strcat() 連線字串。

在 MATLAB 中使用 strcat() 函式連線字串

為了比較兩個字串,我們可以使用 Matlab 內建函式 strcat()。我們需要在函式內部傳遞我們想要連線的字串來連線它們。例如,讓我們建立兩個字串並使用 Matlab 中的函式 strcat() 將它們連線起來。請參閱下面的程式碼。

clc
s1 = "Hello"
s2 = "World"
s3 = strcat(s1,s2)

輸出:

s1 = 

    "Hello"


s2 = 

    "World"


s3 = 

    "HelloWorld"

在輸出中,兩個字串 s1 和 s2 已連線並儲存在 s3 中。我們還可以使用 strcat() 函式連線兩個元胞陣列。在元胞陣列的情況下,該函式會將第一個元胞陣列的第一個條目與第二個元胞陣列的第一個條目以及第一個元胞陣列的第二個條目與第二個元胞陣列的第二個條目連線起來。例如,讓我們建立兩個包含字串的元胞陣列,並使用 strcat() 函式將它們連線起來。請參閱下面的程式碼。

clc
s1 = {'Hello', 'Day'};
s2 = {'World', '10'};
s3 = strcat(s1,s2)

輸出:

s3 =

  1×2 cell array

    {'HelloWorld'}    {'Day10'}

變數 s3 在輸出中包含兩個元素,因為每個元胞陣列中有兩個元素。元胞陣列的大小應相同。否則,會出現錯誤。如你所見,串連時字串之間沒有空格,但我們可以使用包含空格的第三個元胞陣列來放置它。例如,讓我們使用第三個元胞陣列在上述字串之間進行調整。請參閱下面的程式碼。

clc
s1 = {'Hello', 'Day'};
s2 = {'World', '10'};
space = {' '};
s3 = strcat(s1,space,s2)

輸出:

s3 =

  1×2 cell array

    {'Hello World'}    {'Day 10'}

在輸出中,兩個字串之間現在有一個空格。我們可以在兩個字串之間隨意放置任何字串,例如逗號或句號等。我們也可以在字串 s1 或 s2 內放置空格,而不是單獨放置。你還可以使用 + 運算子來連線兩個字串而不是 strcat() 函式,但請確保使用雙引號來定義字串。否則,結果將是數字,因為如果你在單引號中定義字串,Matlab 會將它們視為字元向量。例如,使用雙引號定義兩個字串,使用單引號定義兩個字串,並使用 + 運算子將它們連線起來。請參閱下面的程式碼。

clc
s1 = 'Hello';
s2 = 'World';
s3 = s1+s2
ss1 = "Hello";
ss2 = "World";
ss3 = ss1+ss2

輸出:

s3 =

   159   212   222   216   211


ss3 = 

    "HelloWorld"

由於單引號,第一個輸出是數字,但由於雙引號,第二個輸出是字串形式。

作者: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

相關文章 - MATLAB String