Rail Fence Cipher[Reverse Rail] This page defines a Rail Cipher coding. For this we add a number of "rails", and add the characters in sequence, such as for three rails (taken from Wikipedia): 'WE ARE DISCOVERED. FLEE AT ONCE', gives: W . . . E . . . C . . . R . . . L . . . T . . . E . E . R . D . S . O . E . E . F . E . A . O . C . . . A . . . I . . . V . . . D . . . E . . . N . . to give: WECRL TEERD SOEEF EAOCA IVDEN Try an example of "WE ARE DISCOVERED. FLEE AT ONCE": Try which should give "WECRL TEERD SOEEF EAOCA IVDEN". See the Wiki page for this example (here). |
Examples
- [Example 1 (three rails: WE ARE DISCOVERED. FLEE AT ONCE)]
- [Example 2 (two rails: WE ARE DISCOVERED. FLEE AT ONCE)]
- [Example 3 (one rail: defendtheeastwallofthecastle]
- [Example 4 (three rails: defendtheeastwallofthecastle]
- [Example 5 (two rails: defendtheeastwallofthecastle]
Code
public string railcalc(string s, int rails) { s=s.ToLower(); s = s.Replace('.', ' '); s = s.Replace(',', ' '); s = Regex.Replace(s, " ", ""); string s1 = "", s2 = "", s3 = ""; ViewData["code1"] = ""; ViewData["code2"] = ""; ViewData["code3"] = ""; for (int i = 0; i < s.Length; i+=4) { string ss = s.Substring(i, 1); try { s1 += ss; } catch { s1 += ss; } } for (int i = 1; i < s.Length; i += 2) { string ss = s.Substring(i, 1); try { s2 += ss; } catch { s2 += ss; } } for (int i = 2; i < s.Length; i += 4) { string ss = s.Substring(i, 1); try { s3 += ss; } catch { s3 += ss; } } s1 = s1 + s2 + s3; string result=""; for (int i = 0; i < s1.Length; i++) { result+= s1[i]; if (i % 5 == 4) result += " "; } return (result.ToUpper()); }