---
title: "Implement a program to generate all possible permutations of a given string."  
description: "Implement a program to generate all possible permutations of a given string."  
author: "Utpal Vishwas"  
published: 2023-06-14  
updated: 2023-06-15  
canonical: https://www.mindstick.com/forum/158750/implement-a-program-to-generate-all-possible-permutations-of-a-given-string  
category: "c#"  
tags: ["c#", "string", "programs"]  
reading_time: 2 minutes  

---

# Implement a program to generate all possible permutations of a given string.

Implement a [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) to [generate all possible permutations](https://www.mindstick.com/forum/158802/implement-a-rust-program-to-generate-all-possible-permutations-of-a-given-string) of a given string.

## Replies

### Reply by Aryan Kumar

Sure, here is the C# code to implement a program to generate all possible [permutations](https://www.mindstick.com/interview/34418/random-permutations-using-numpy) of a given string:

C#

```plaintext
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.


---

Original Source: https://www.mindstick.com/forum/158750/implement-a-program-to-generate-all-possible-permutations-of-a-given-string

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
