0

I'm studying for my first test in C# (beginner). I have a problem with assingments where I'm supposed to create a new array using loops. For example this task where the task is to write a method that recieves a sentence(string) and a letter(char). The method must then identify at which index positions the letter occurs at in the sentence and then place these positions in a array. For example, we have the short sentence "Hello world!" and the letter 'o' then the array should contain 4 (the index position of the first instance) and 7 (the index position of the second instance).

I'm not allowed to use built-in methods except for .Length, Console.WriteLine..

You can see my code below. It is not working at all. I want it to print out "4, 7, "

static void Main(string[] args)
{
    int[] result = IndexesOfChar("Hello world", 'o');
    for(int i = 0; i<result.Length; i++)
    {
        Console.Write(result[i] + ", ");
    }
}

static int[] IndexesOfChar(string sentence, char letter)
{
    int count = 0;
    int[] newArr = new int[count];

    for(int i =0; i < sentence.Length; i++)
    {
        if(sentence[i] == letter)
        {
            newArr[count] = i;
            count++;
        }
        
    }
    return newArr;
}
3
  • 2
    There's no way you can create newArr at the start because you don't know how many instances of 'letter' you are going to find. Personally, I'd use a List<int> and add to it, and then convert to an array at the end of the method, but I guess that's too advanced for your test. Commented Oct 27, 2022 at 10:08
  • Your code won't work because you are creating an array of zero length. Its length will not change when you try to add an element at an index that is greater than the length. If you are not allowed to use a more dynamic collection type like List<int>, and you are also not allowed to use the Arrays.Resize method, your only option is to create a new array each time an element is about to be added. Commented Oct 27, 2022 at 10:17
  • cHANGE TO int[] newArr = new int[sentence.Length; Commented Oct 27, 2022 at 10:24

3 Answers 3

1

The problem is that you don't know the array Length beforehand. So you have to compute count and only then create the array:

static int[] IndexesOfChar(string sentence, char letter) 
{
    // Required array length computation:
    int count = 0;

    for (int i = 0; i < sentence.Length; i++)
        if (sentence[i] == letter)
            count++;
 
    // We know count, we are ready to create the array:
    int[] newArr = new int[count];

    // Finally, we fill in the array
    // let do not re-use count, but declare separate index variable
    int index = 0;

    for (int i = 0; i < sentence.Length; i++)
        if (sentence[i] == letter)
            newArr[index++] = i;

    return newArr;     
}

Your task is not a good example for arrays, usually we put List<T> when we don't know size:

using System.Linq;

...

static int[] IndexesOfChar(string sentence, char letter) {
  List<int> result = new List<int>();

  for (int i = 0; i < sentence.Length; ++i)
    if (sentence[i] == letter)
      result.Add(i); // <- unlike array we can just Add a new item

  // create an array from list with a help of Linq
  return result.ToArray();
}
Sign up to request clarification or add additional context in comments.

Comments

0

It is not working, because in the method IndexesOfChar, you create an array with a length of count (that is at that point is zero). You can't modify an array's length once you declared it.

If you can't use any built in methods, I suggest you to declare the newArr as a list. This is what you should fill the indexes into, then create an array, and fill the list's values into that array with another for loop.

Comments

0

Unlike type List, you can't change the size of an array, so you can't do newArr[count] = i; because the size of newArr is 0. Instead if you only want to use arrays, you can reassign newArr with its old value + the new integer :

static void Main(string[] args)
{
    int[] result = IndexesOfChar("Hello world", 'o');
    for(int i = 0; i<result.Length; i++)
    {
        Console.Write(result[i] + ", ");
    }
}

static int[] IndexesOfChar(string sentence, char letter)
{
    int count = 0;
    int[] newArr = new int[count];

    for(int i =0; i < sentence.Length; i++)
    {
        if(sentence[i] == letter)
        {
            var updateArr = new int[newArr.Length + 1];
            for (int j = 0; j < newArr.Length; j++)
            {
                updateArr[j] = newArr[j];
            }
            updateArr[newArr.Length] = i;
            newArr = updateArr;
            count++;
        }
        
    }
    return newArr;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.