8.3. Array Methods¶
As with strings, C# provides us with useful methods for arrays. These methods will either alter an existing array, return information about the array, or create and return a new array.
8.3.1. Common Array Methods¶
Here is a sample of the most frequently used array methods. More complete lists can be found here:
To see detailed examples for a particular method, control-click (or right-click) on its name.
Method |
Syntax |
Description |
---|---|---|
|
Returns the index of the FIRST occurrence of an item in the array. |
|
|
Returns the index of the LAST occurrence of an item in the array. If the item is not in the array, -1 is returned. |
|
|
Returns the value of specified index. |
Method |
Syntax |
Description |
---|---|---|
|
Reverses the order of the elements in an array. |
|
|
Arranges the elements of an array into increasing order. |
Method |
Syntax |
Description |
---|---|---|
|
Adds of Removes indicies based on desiredLength value. |
Method |
Syntax |
Description |
---|---|---|
|
Updates index value with new item. |
|
|
Updates index value with new item. |
Method |
Syntax |
Description |
---|---|---|
|
Combines all the elements of an array into a string. |
|
|
Divides a string into smaller string pieces, which are stored in a new array. |
|
|
Divides a string into chars, which are stored in a new array. |
8.3.2. Check Your Understanding¶
Follow the links in the table above for the Sort
, Reverse
, Split
and
Join
methods. Review the content and then answer the following questions.
Question
What is printed by the following code?
1 2 3 4 5 6 7 | string[] charles = {"coder", "Tech", "47", "23", "350"};
Array.Sort(charles);
Console.WriteLine(charles[0]);
Console.WriteLine(charles[1]);
Console.WriteLine(charles[2]);
Console.WriteLine(charles[3]);
Console.WriteLine(charles[4]);
|
"350", "23", "47", "Tech", "coder"
"coder", "Tech", "23", "47", "350"
"23", "47", "350", "Tech", "coder"
"23", "350", "47", "coder", "Tech"
Question
Which statement converts the string string phrase = "LaunchCode students rock!"
into the array string[] words = {"LaunchCode", "students", "rock!"}
?
string.Join(" ", phrase);
phrase.Split(" ");
string.Join("", phrase);
phrase.Split("");
Question
What is printed by the following program?
1 2 3 4 5 6 7 8 9 10 | string[] groceryBag = {"bananas", "apples", "edamame", "chips", "cucumbers", "milk", "cheese"};
string[] selectedItems = new string[4];
Array.Copy(groceryBag, selectedItems, 4);
Array.Sort(selectedItems);
Console.WriteLine(selectedItems[0]);
Console.WriteLine(selectedItems[1]);
Console.WriteLine(selectedItems[2]);
Console.WriteLine(selectedItems[3]);
|
"apples", "bananas", "edamame", "chips"
"chips", "cucumbers", "edamame", "milk"
"apples", "banana", "chips", "edamame"
"cheese", "chips", "cucumbers", "edamame"