w3resource

C#: Create a new string made of every other character starting with the first from a given string


Every Other Character in String

Write a C# Sharp program to create a string made of every other character starting with the first in a given string.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Create a new string made of every other character starting with the first from a given string.

Sample Solution:-

C# Sharp Code:

using System;

// Namespace declaration
namespace exercises
{
    // Class declaration
    class Program
    {
        // Main method - entry point of the program
        static void Main(string[] args)
        {
            // Displaying the output of the 'test' method with different string inputs
            Console.WriteLine(test("Python")); // Output: Pto
            Console.WriteLine(test("PHP"));    // Output: PP
            Console.WriteLine(test("JS"));     // Output: J
            Console.ReadLine(); // Keeping the console window open
        }

        // Method to return a new string containing characters at even indices from the input string
        public static string test(string s)
        {
            var result = string.Empty; // Variable to store the resulting string

            // Loop through the characters of the input string
            for (var i = 0; i < s.Length; i++)
            {
                // Check if the current index 'i' is even
                if (i % 2 == 0)
                {
                    // Append the character at index 'i' to the result string
                    result += s[i];
                }
            }

            return result; // Return the string containing characters at even indices
        }
    }
}

Sample Output:

Pto
PP
J

Flowchart:

C# Sharp: Flowchart: Create a new string made of every other character starting with the first from a given string.

For more Practice: Solve these Related Problems:

  • Write a C# program to construct a string using every third character starting from the first in a given string.
  • Write a C# program to create a new string by skipping one character after every two characters in a string.
  • Write a C# program to reverse the given string and extract every other character.
  • Write a C# program to create a string using characters at even indices only, excluding vowels.

Go to:


PREV : First 'a' Followed by Another 'a'.
NEXT : Cumulative Substrings.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.