DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rail Fence Cipher

05.24.2008
| 5571 views |
  • submit to reddit
        Implementation

		public static string RailFenceCipher(string input){
			// b.t.w we only use two rails
			string rail1 = "";
			string rail2 = "";
			char[] arry = input.ToCharArray();
			bool top = true;
			foreach(char ch in arry){
				if(top == true)
					rail1 += ch.ToString();
				else
					rail2 += ch.ToString();
				top = !top;
			}
			return rail1 + rail2;
		}
		public static string DeRailFenceCipher(string input){
			// b.t.w we only use two rails
			string rail1 = input.Substring(0,input.Length / 2);
			string rail2 = input.Substring(input.Length / 2);
			int r1 = 0;
			int r2 = 0;
			string o = "";
			bool top = true;
			while(o.Length != input.Length){
				if(top == true){
					o += rail1.Substring(r1, 1);
					r1 ++;
				}
				else{
					o += rail2.Substring(r2, 1);
					r2 ++;
				}
				top = !top;
			}
			return o;
		}