iT邦幫忙

2026 iThome 鐵人賽

DAY 3
0

字串基礎用法:

System.Console.WriteLine(”Hello World”);

顯示 Hello World 這句話


字串換行:

如果字串要換行有兩種方法

第一種:

System.Console.WriteLine(”Hello World”);
System.Console.WriteLine(”Mr.Write”);

顯示上行 Hello World,下行 Mr.Write


第二種:/n

如果覺得要每一行都寫有點麻煩,且會造成程式碼過多,所以想在同一行中,就可以有換行功能,可以在小括弧裡前面寫完後,加入 \n,在後面打想要的內容,就可以達到跟第一種一樣的換行功能

System.Console.WriteLine(”Hello World /nMr.Write”);

字串中間加入特殊符號:\

如果想在字串中間加入特殊符號,像是在Hello World和Mr.Write中間加入”,一般人可能會直接這樣寫

System.Console.WriteLine(”Hello World”Mr.Write”);

在這樣寫,會發現執行後會出現錯誤,為什麼呢?
主要是因為它會先判斷”Hello World”為一個字串,而Mr.Write”不符合字串的規定而使程式報錯

正確方式要在中間想要加的特殊符號前加入 \,才可以正常顯示

System.Console.WriteLine(”Hello World\” Mr.Write”);

顯示 Hello World” Mr.Write


利用字串變數結合:+

如果想要利用變數來與其他字串結合,可以用 變數名稱 + 字串名稱or其他字串變數名稱,來做使用

string name = “Hello”;   //設定字串Hello為名為name的變數
System.Console.WriteLine( name + “World”);

顯示 Hello World


顯示字串長度:Length

想要知道該字串的的字數,可以在字串後面加入 .Length

string name = “Hello World”;
System.Console.WriteLine( name.Length );

顯示 Hello World 的字數,顯示11 (包含空格)


轉換成大寫小寫:ToUpper()、ToLower()

想讓字串整個英文字調整成全部大寫或全部小寫,可以在後面加入 .ToUpper() 或 .ToLower()

ToUpper():全部變大寫

string name = “Hello World”;
System.Console.WriteLine( name.ToUpper() );

將 Hello World 轉換成大寫,顯示 HELLO WORLD

ToLower():全部變小寫

string name = “Hello World”;
System.Console.WriteLine( name.ToLower() );

將 Hello World 轉換成小寫,顯示 hello world


判斷字串是否含有特定的子字串:Contains()

如果想要搜尋該文字有沒有出現在字串當中,可以在後面加入 .Contains()

string name = “Hello World”;
System.Console.WriteLine( name.Contains(”Hello”) );

判斷 Hello World 是否含有 Hello 這個詞,有的顯示 True,否則顯示 False


判斷特定位置的值:[]

如果想知道該字串第幾個的字是什麼,可以在後面加入 [ ],在中括弧內可加入數字,這個數字代表字串的第幾個單字

string name = “Hello World”;
System.Console.WriteLine( name[0] ); /C#世界,第一個單字從0開始算

判斷 Hello World 第一個單字,顯示 H


判斷特定值的位置:IndexOf()

跟上述相反,如果是想知道改單字在字串中哪個位置,可以在後面加入 .IndexOf(),並在括弧內輸入字串中的文字

string name = “Hello World”;
System.Console.WriteLine( name.IndexOf(’H’) );

判斷 Hello World 中的 H 單字的位置,顯示 0

如果打字串的話,會顯示該字串開頭的字位置
如果打字串上沒有的字,會顯示 -1


切割字串:Substring()、Substring(,)

如果只想顯示字串中特定的幾個字,可以在後面加上Substring() 或 Substring(, )
Substring():從第幾個字母開始

Substring():從第幾個字母開始

string name = “Hello World”; 
System.Console.WriteLine( name.Substring(2) );

從第二個字母開始,到最後,顯示 llo World

Substring():從第幾個字母開始

string name = “Hello World”; 
System.Console.WriteLine( name.Substring(2, 3) );

Hello World 從第二個單字做切割,並只留切割後三個單字,顯示 llo


心得:

今天學習了關於字串的不同用法,雖然很多分類,且有些不一定會在遊戲程式中使用到,但把這些學起來,可以運用到其他程式中,也可以方便用於搜尋和改變字串內容。以上是今日學習的內容,明天會學習到數字(整數、浮點數)的用法,那我們就明天見吧~


參考影片

【C#】3小時初學者教學 |Csharp | C# 教學 | C# 入門 | C++++
YouTube頻道:GrandmaCan -我阿嬤都會
影片段落: 34:05 ~ 48:40 (時間段已設定好)
Yes


上一篇
【Day2】學習常見的資料型態與變數
下一篇
【Day4】學習數字用法
系列文
從 Hello World 學習 C#,到看懂AI生成的遊戲程式碼5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言