Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing letters in a group of fours from a string

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

For example:

string sequence = "GnatBatsFish"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading