iT邦幫忙

2024 iThome 鐵人賽

DAY 3
0
自我挑戰組

C# 由淺入深系列 第 3

Day3 Array 3

  • 分享至 

  • xImage
  •  

Array.Clear()

Array.Clear() 是 C# 中用來清除陣列中指定範圍的元素的方法。它會將指定範圍的所有元素設置為該陣列元素類型的預設值。例如,對於數字類型(如 int),預設值是 0;對於字串類型,預設值是 null。

public static void Clear(Array array, int index, int length)
  • array: 需要進行清除的陣列。
  • index: 從哪個索引位置開始清除。
  • length: 要清除的元素數量。

假設你有一個整數陣列,並且你想要將其中的一部分元素清除(即設置為 0):

using System;

class Program
{
    static void Main()
    {
        // 宣告並初始化整數陣列
        int[] numbers = { 1, 2, 3, 4, 5 };

        // 輸出清除前的陣列
        Console.WriteLine("清除前:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine();

        // 使用 Array.Clear() 方法清除陣列中的一部分元素
        // 這裡我們從索引 1 開始,清除 3 個元素
        Array.Clear(numbers, 1, 3);

        // 輸出清除後的陣列
        Console.WriteLine("清除後:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
    }
}

Output:
        清除前:
        1 2 3 4 5 
        清除後:
        1 0 0 0 5 

對於其他類型的預設值:

  • bool,預設值是 false。
  • string,預設值是 null。
  • 對於參考型別(例如對象),預設值也是 null。

Array.IndexOf()

Array.IndexOf() 是 C# 中一個用於查找數組中特定元素位置的方法。它返回該元素在數組中的索引位置,如果找不到該元素則返回 -1。這個方法是靜態方法,屬於 System.Array 類,並且可以用於任何類型的數組。

基本概念

  • 定義:Array.IndexOf() 方法在數組中搜索指定的元素,並返回該元素第一次出現的索引。
  • 用途:這個方法用於查找數組中某個元素的位置,適用於處理需要快速定位元素的情況,如搜索和數據匹配等。
using System;

class Program
{
    static void Main(string[] args)
    {
        // 定義一個整數數組,包含一些預設的數字
        int[] numbers = new int[]
        {
            90, 199, 22, 50, 30
        };

        // 提示用戶輸入要搜尋的數字
        Console.WriteLine("請輸入你要搜尋的數字:");

        // 從用戶的輸入讀取一個數字,並將其轉換為整數
        int search = Convert.ToInt32(Console.ReadLine());

        // 使用 Array.IndexOf() 方法查找數組中的數字
        // 這裡我們指定從索引 1 開始,在索引範圍 1-2 中查找
        // 也就是說,它只會在 { 199, 22 } 這兩個數字中查找
        int position = Array.IndexOf(numbers, search, 1, 2);

        // 檢查找到的索引值是否大於 -1,表示數字是否存在於指定範圍內
        if (position > -1)
        {
            // 如果找到了數字,顯示數字和其在數組中的位置
            // position + 1 是因為索引從 0 開始,但我們想顯示從 1 開始的位置信息
            Console.WriteLine($"Number {search} has been found at position {position + 1}");
        }
        else
        {
            // 如果找不到數字,告訴用戶數字不在範圍內
            Console.WriteLine($"Number {search} has not been found");
        }
    }
}

假設數組為 { 90, 199, 22, 50, 30 }:

用戶輸入 199,則輸出:Number 199 has been found at position 2。
用戶輸入 22,則輸出:Number 22 has been found at position 3。
用戶輸入 50,則輸出:Number 50 has not been found(因為查找範圍是索引 1 到 2)。
用戶輸入 90,則輸出:Number 90 has not been found(因為查找範圍是索引 1 到 2)。


上一篇
Day2 Array 2
下一篇
Day4 Array 4 + List1
系列文
C# 由淺入深7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言