Sure, here is the C# code to implement a program to generate all possible permutations of a given string:
C#
using System;
public class Permutations
{
public static IEnumerable<string> Permute(string str)
{
if (str.Length == 1)
{
yield return str;
}
else
{
for (int i = 0; i < str.Length; i++)
{
string prefix = str.Substring(0, i);
string suffix = str.Substring(i + 1);
foreach (string perm in Permute(suffix))
{
yield return prefix + perm;
}
}
}
}
public static void Main(string[] args)
{
string str = "ABC";
foreach (string perm in Permute(str))
{
Console.WriteLine(perm);
}
}
}
This program first checks if the given string is of length 1. If it is, then the program simply yields the string back. Otherwise, the program iterates through all the characters in the string. For each character, the program calls the
Permute() function recursively to generate all possible permutations of the remaining characters. The results of the recursive calls are then combined to generate all possible permutations of the original string. The
Main() method then prints all the possible permutations of the string to the console.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is the C# code to implement a program to generate all possible permutations of a given string:
C#
This program first checks if the given string is of length 1. If it is, then the program simply yields the string back. Otherwise, the program iterates through all the characters in the string. For each character, the program calls the
Permute()function recursively to generate all possible permutations of the remaining characters. The results of the recursive calls are then combined to generate all possible permutations of the original string. TheMain()method then prints all the possible permutations of the string to the console.