Home > database >  Printing letters in a group of fours from a string
Printing letters in a group of fours from a string

Time:12-20

I am trying to print the letters from this string in groups of four.

For example:

string sequence = "GnatBatsFish"

I am trying to get the letters to print out like this:

Gnat Bats Fish

I've tried to attempt this with the code below but it just ends up printing the first letter of each word in the string:

 string sequences = "GnatBatsFish";

            int test = 4;
            int j;
            for (j = 0; j < test; j  )
            {
                Console.WriteLine(sequences[j]);
                j  = 3;
                test  = 3;
                
            }

Outputs:

G B F

CodePudding user response:

To fix this, you can use the Substring method to extract substrings of 4 characters from the input string, and then print each substring. Here's an example of how you could do this:

string sequence = "GnatBatsFish";

for (int i = 0; i < sequence.Length; i  = 4)
{
    string substring = sequence.Substring(i, Math.Min(4, sequence.Length - i));
    Console.WriteLine(substring);
}

This code uses a loop to iterate through the input string, extracting substrings of 4 characters at a time. The Substring method takes two arguments: the start index and the length of the substring. The start index is incremented by 4 on each iteration of the loop, so that the next substring starts 4 characters after the previous one. The length of the substring is the minimum of 4 and the remaining length of the input string (to handle the case where the input string is not a multiple of 4 characters in length).

With this code, the output will be:

Gnat
Bats
Fish
  • Related