不學 JAVA 換學 C# 之覺得心累 - L1:ch11 常見類別的屬性和方法
Console 類別
- WriteLine(string value):在控制台上輸出資料,並提供換行。
- ReadLine()::從控制台讀取一行資料。
範例:
1 | Console.WriteLine("請輸入您的名字:"); |
String 類別
- Length:獲得字串的長度。
- Substring(int startIndex, int length):擷取字串中的一部分。
- Replace(string oldValue, string newValue):將某些字符替換為其他值。
- Contains(string value):檢查字串是否包含特定子字串。
- Concat(params string[] values):將多個字串連接在一起。
- Format(string format, params object[] args):格式化字串。
- Split(params char[] separator):根據分隔符將字串分割成陣列。
- Join(string separator, params string[] values):將陣列中的元素,加入分隔符連接成一個字串。
- IsNullOrEmpty(string value):檢查字串是否為 null 或空字串。
- IsNullOrWhiteSpace(string value):檢查字串是否為 null、空字串或只包含空白字符。
範例:
1 | string text = "Hello, World!"; |
Math 類別
- Abs(double value):求絕對值。
- Pow(double x, double y):計算次方值。
- Sqrt(double value):求平方根。
範例:
1 | double number = -9.5; |
Array 類別
T 可以是任何型態或類別,例如:int[] array
、Person[] array
。
- Length:計算陣列元素的個數。
- Sort(T[] array):將陣列進行排序 (由小到大)。
- Reverse(T[] array):反轉陣列順序。
- IndexOf(T[] array, T value):回傳指定元素在陣列中的索引值,如果找不到則回傳 -1。
- LastIndexOf(T[] array, T value):回傳最後一個出現的指定元素的索引。
- Clear(T[] array, int index, int length):將陣列中指定範圍的元素設為預設值。數值型會變成 0,參考類型會變成
null
。 - BinarySearch(T[] array, T value):對已排序的陣列進行二分搜尋。
BinarySearch
使用之前陣列一定要排序好,否則結果不正確。回傳在陣列中的索引位置,或回傳一個負數。回傳值的定義:
The index of the specified
value
in the specifiedarray
, ifvalue
is found; otherwise, a negative number. Ifvalue
is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger thanvalue
. Ifvalue
is not found andvalue
is greater than all elements inarray
, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sortedarray
, the return value can be incorrect and a negative number could be returned, even ifvalue
is present inarray
.如果
value
存在於陣列中,則回傳value
在陣列中的索引位置;否則,回傳一個負數。如果value
不存在,且value
小於陣列中的一個或多個元素,則回傳的是 bitwise complement 的值,這個值是第一個比value
大的元素的索引。如果value
不存在,且value
大於陣列中所有元素,則回傳的是最後一個元素索引 +1 的 bitwise complement。
範例:
1 | int[] numbers = { 3, 1, 4, 1, 5 }; |
參考資料:
Array.BinarySearch Method
Bitwise and shift operators (C# reference)