Learning to Code — Part 7b: Arrays & Strings

JAGGED ARRAYS

Continuing on with Arrays & Strings, we’re going to purposely give ourselves a headache, by talking about jagged arrays. Apparently, “jagged” arrays are arrays of arrays. Here’s what the code looks like:

int[ ][ ] jaggedArr = new int[3][ ];

This code declares a new single-dimensional array called jaggedArr, who has 3 elements, each of which is a single-dimensional array of integers. So, above is how you’d create the jagged array but without any initial values. Below is code that creates a jagged array with initial values. Since there are 3 internal arrays being created, it appears that we don’t have to put the number 3 in the first line.

int[ ][ ] jaggedArr = new int[ ][ ] {
new int[ ] {1,8,2,7,8},
new int[ ] {2,4,6},
new int[ ] {33,42}
};

The app then goes into how you can access individual array elements:

int x = jaggedArr[2][1]

Now, it says that running this will result in x = 42. I thought I’d have to hit the Try It Yourself, but let me try to figure this out first:

  • It looks like the first number in the bracket, 2, is telling you to look within the array at index position 2, which would be the third array.
  • Then, the second number in the bracket, 1, is telling you to look at the value at index position 1, which would be the second number.

If my assumption is correct then, yes, x would equal 42. I’m going to hit the Try It Yourself button, change the code to be the int x = jaggedArr[1][2], hit the RUN button, and see if the result is 6. Here goes…

YES!!! I was right! OK, good feelings are pouring over me now! One last thing they describe within this section is that a…

jagged array is an array-of-arrays, so an int[ ][ ] is an array of int[ ], each of which can be of different lengths and occupy their own block of memory.

They compare this to…

…how a multidimensional array (int[ , ]) is a single block of memory (essentially a matrix). It always has the same amount of columns for every row.

ARRAY PROPERTIES

You can retrieve individual properties of an array, like it’s length (which is the number of elements in the array) and it’s rank (which is the number of dimensions of the array). Like any other class member, we use the dot next to the name of the array, like this:

int[ ] arr = {2, 4, 7};
Console.WriteLine(arr.Length);

When run, this code prints the number 3 (for the fact that the arr array has 3 elements) to the screen.

Console.WriteLine(arr.Rank);

This code will print the number 1 (for the fact that arr is a single-dimensional array) to the screen. The SoloLearn app also shows how the Length property can be used within for loops when specifying the number of times the loop should run, like this:

int[ ] arr = {2, 4, 7};
for(int k = 0; k < arr.Length; k++) {
Console.WriteLine(arr[k]);
}

When run, this code will:

  • Create an integer-based array called arr, with the following 3 values: 2, 4 and 7 (in that order).
  • The for loop begins by creating a variable called k, with a data type of integer, and an initial value of 0.
  • It then checks to see if the current value of k is less than the length of the array called arr, which translates into checking if 0 is less than 3 (because there are 3 elements within the array, meaning it’s length is 3).
  • Since it is, it executes the next line, which is to print the value of the element residing at the index “k” position within the array called arr. This translates into the value of the element residing at the index 0 position within the array called arr, which equals 2. So, 2 is printed to the screen.
  • The value of k is incremented from 0 to 1, and then the check of whether k is less than the length of the arr array occurs, or, is 1 less than 3?
  • Since it is, it executes the next line, which is to print the value of the element residing at the index “k” position within the array called arr. This translates into the value of the element residing at the index 1 position within the array called arr, which equals 4. So, 4 is printed to the screen.
  • The value of k is incremented from 1 to 2, and then the check of whether k is less than the length of the arr array occurs, or, is 2 less than 3?
  • Since it is, it executes the next line, which is to print the value of the element residing at the index “k” position within the array called arr. This translates into the value of the element residing at the index 2 position within the array called arr, which equals 7. So, 7 is printed to the screen.
  • The value of k is incremented from 2 to 3, and then the check of whether k is less than the length of the arr array occurs, or, is 3 less than 3?
  • Since it’s not, the for loop ends, and we reach the end of the code.

Similarly, there are three methods that can be called when working with arrays:

  • Max returns the largest value of the array, like this:
int[ ] arr = { 2, 4, 7, 1};
Console.WriteLine(arr.Max());
  • This code creates an integer-based array called arr, with the following 4 values: 2, 4, 7 and 1 (in that order).
  • It then prints the largest number to the screen, which is 7.
Console.WriteLine(arr.Min());
  • This code prints the smallest number to the screen, which is 1.
Console.WriteLine(arr.Sum());
  • This code prints the sum of all of the numbers within the array to the screen, which is 14.

WORKING WITH STRINGS

The app talks about how, while strings might be thought of as arrays of characters, in reality, they’re objects. In other words, when you declare a string variable, you’re instantiating an object of data type string. Because of this, there are a number of built-in methods that go along with it. They are:

  • Length — returns the length of the string.
string a = “some text”;
Console.WriteLine(a.Length);
Output: 9
  • IndexOf(value) — returns the index of the first occurrence of the value within the string.
Console.WriteLine(a.IndexOf(‘t’));
Output: 5
  • Insert(index, value) — inserts the value into the string starting from the specified index.
a = a.Insert(0, “This is “);
Console.WriteLine(a);
Output: “This is some text”
  • Replace(oldValue, newValue) — replaces the specified value in the string.
a = a.Replace(“This is” , “I am”);
Console.WriteLine(a);
Output: “I am some text”
  • Contains(value) — returns true if the string contains the specified value.
if(a.Contains(“some”))
Console.WriteLine(“found”)
Output: “found”
  • Remove(index) — removes all characters in the string after the specified index.
a = a.Remove(4);
Console.WriteLine(a);
Output: “I am”
  • Substring(index, length) — returns a substring of the specified length, starting from the specified index. If the length in not specified, the operation continues to the end of the string.
a = a.Substring(2);
Console.WriteLine(a);
Output: “am”

The app goes on to describe how you can access the specific characters of a string by its index position in the same way that you would access the individual elements of an array:

string a = “some text”;
Console.WriteLine(a[2]);

When executed, this code creates a variable called a, with a data type of string, and sets it’s initial value to some text. The it prints to the screen the character within the string-based variable at index position 2, which is m.

Finally, they want us to create a program that will:

  • Take a string,
  • Replace all occurrences of the word “dog” with “cat”, and
  • Output the first sentence only.

I’ve started a new console app in Visual Studio called stringTest. Here are my thoughts:

  • First, within the Main method, create a string-based variable and set it’s initial value to a sentence that includes the word “dog” several times. Followed by a second sentence.
  • Call a method that will replace the word “dog” for the word “cat”.

Before the last part, only returning the first sentence, I wrote the following code, which worked:

static string DogToCat(string sentence) {
sentence = sentence.Replace(“dog”, “cat”);
return sentence;
}
static void Main(string[] args) {
string x = DogToCat(“This is a sentence that has the word dog multiple times because I have a dog. Her name is Indy.”);
Console.WriteLine(x);
Console.ReadLine();
}

When run, this code prints both sentences to the screen, replacing the two instances of the word dog with the word cat. The last part, only returning the first sentence, is going to take a little thought:

  • The period at the end of the first sentence obviously marks its end, but I need to remove everything from one space after that point.

So, let’s try this:

  • Get the position of the period, and then add 1 to it:
int a = sentence.IndexOf(“.”) + 1;

…and then I like to add the test of printing the value to the screen to see if it’s what I expect it to be:

Console.WriteLine(a);
Console.ReadLine();

I literally counted the characters to find that the period was in index position 76 and, after adding 1, I get 77. When the code is executed, 77 is printed to the screen, so that’s good.

  • Next, I want to remove every character, starting at index position 77, all the way to the end:
string firstSentence = sentence.Remove(a);
  • And then I changed return sentence to be return firstSentence.

When executed, it prints out the first sentence, with the words dog replaced by the word cat. In other words…IT WORKED!! It is worth mentioning that the SoloLearn app did it slightly differently. Instead of:

int a = sentence.IndexOf(“.”) + 1;
string firstSentence = sentence.Remove(a);

They wrote:

sentence = sentence.Substring(0, text.IndexOf(“.”)+1);

It looks like this translates into:

  • Take the substring, of the string-based value of the variable sentence, starting at index position 0, and going to the index position of the location of “.”, plus 1, in other words, 77.

I can definitely see how this solution is faster, and done in one line versus two.

So this wraps up Strings & Arrays. In the next article, we’ll move on to the last section that I had gotten up to previously, which is called More On Classes (which definitely, in my mind, makes me think, Moron Classes…sigh, I’m such a child).

Anyway, as always, please correct anything I’ve gotten wrong (either slightly or very) and, here’s a link to the previous article, Learning to Code — Part 7a: Arrays & Strings.