My own string scramber

So, I’ve been mostly skipping through the videos in this section and just doing things my own way. Generally just referencing back to see how Ben did things compared to me (I use way more switch statements!). I’ve been coding for a while now, so didn’t really need the extra support that these early lectures provide.

So when it came to the actual scrambling of the anagrams, I wasn’t 100% sure were the provided method was given and figured it couldn’t be that hard to just knock up one of my my own.

Note: if you’re new to coding, don’t be scared.
Pretty much none of the techniques used here have been covered in the course yet (I can’t imagine StringBuilder will be touched on at all - It’s basically the same as a string but isn’t immutable).

So here it is:

string Scramble (string input) {
		StringBuilder output = new StringBuilder();
		output.Append(input);
		
		for (int i = 0; i < input.Length; i++) {
			int rand = Random.Range(0, input.Length);
			char temp = output[i]; 
			output[i] = output[rand];
			output[rand] = temp;
		}

		return(output.ToString());
	}

Pretty straight forward to be honest. It takes in a string of any length and then iterates through each character, swapping it with another one at random.

Here’s a few of the results it produces when providing an input of GAMEDEV:

1 Like

Impressive!

1 Like

I also didn’t know how the Anagram function was defined. It’s my first time programming in C#, but the IDE told me it is an “(extension)”.

If you hover over the Method and press F12 it will take you to where that methods defined so you can take a peek!