I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.
All this method does is combining the entire sentence and give them index starting from zero.
it then separates the even indexed characters into an array and the odd ones into a different array .
When I convert the two arrays to strings and then place them in a textbox only the first string shows up.
private void ZigzagBu_Click(object sender, EventArgs e) {
string s = PlaintextTB.Text;
s = s.Replace(" ","");
char[] whole = s.ToCharArray();
char[] even = new char[whole.Length];
char[] odd = new char[whole.Length];
int evenIndex = 0;
int oddIndex = 0;
for(int i =0;i<whole.Length;i++) {
if (i % 2 == 0) {
even[evenIndex] = whole[i];
evenIndex++;
}
else {
odd[oddIndex] = whole[i];
oddIndex++;
}
}
s = new String(even);
string m = new String(odd);
CiphertextTB.Text = s+m;
}
The problem was in the size of the char arrays. I solved it by <br/>
char[] even = new char[whole.Length/2];
char[] odd = new char[whole.Length/2];
Actually, your code is over complicated.
The same thing can be done with simple strings, no need to convert to char arrays:
var s = "0123456";
var even = "";
var odd = "";
for(int i=0; i<s.Length;i++)
{
if(i % 2 == 0)
{
even += s[i];
}
else
{
odd += s[i];
}
}
var result = even + odd;
However, if your plain text string is even a bit long (say, 10, 20 chars) - a better implementation would be to use StringBuilder:
var s = "0123456";
var even = new StringBuilder();
var odd = StringBuilder();
for(int i=0; i<s.Length;i++)
{
if(i % 2 == 0)
{
even.Append(s[i]);
}
else
{
oddAppend(s[i]);
}
}
var result = even.Append(odd.ToString()).ToString();
Use of StringBuilder class is more elegant approach instead of creating 2 instances of String.
Implementation: DotnetFiddler
Related
I'm doing an exercise that says I have to enter a phrase and put it in array, then I have to delete all the repeated characters and show the new phrase.
I did it like this but I don't know how to get char from string array and put it into another string array.
PS: I must only use the basics of C# and arrays :(
namespace Exercice3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Entrez une phrase SVP!!");
string phrase = Console.ReadLine();
string[] phraseArray = new string[]{ phrase };
string[] newPhrase = new string[phrase.Length];
for (int i = 0; i <= phrase.Length - 1; i++)
{
for (int j = 1; j <= phrase.Length - 1; j++)
{
if (phraseArray[i] != phraseArray[j])
newPhrase = phraseArray[i]; //Probleme here
}
}
Console.WriteLine(newPhrase);
}
}
}
something like this would do it. You don't have to do it this way...
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var newColl = new List<char>();
foreach(char c in "aaabbbccc".ToCharArray())
{
if (!newColl.Contains(c))
newColl.Add(c);
}
Console.WriteLine(new string(newColl.ToArray()));
}
}
Output:
abc
Array-only method
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const string orig = "aaabbbcccddd";
int origLen = orig.Length;
char[] newArr = new char[origLen]; // get max possible spots in arr
int newCount = 0;
for(int i = 0; i < origLen; i++)
{
bool yes = false;
for(int j = 0; j < newCount + 1; j++)
{
if (newArr[j] == orig[i])
{
yes = true;
break;
}
}
if (!yes)
{
newArr[newCount] = orig[i];
newCount++;
}
}
Console.WriteLine(new string(newArr));
}
}
Output:
abcd
The main problem here is that you are using arrays of strings. That is inappropriate because you are trying to iterate the characters of the string.
You need to construct your array of characters like this:
char[] phraseArray = phrase.ToCharArray();
This should allow you the ability to iterate the set of characters, check for duplicates, and form the new character array.
The reason why you're getting an IndexOutOfRangeException is because if you look at the two arrays:
string[] phraseArray = new string[]{ phrase };
And
string[] newPhrase = new string[phrase.Length];
The length of both arrays are completely different, phraseArray has a length of 1 and newPhrase will be set to the length of your phrase, so if you insert a world of more than 1 character both arrays will not match and then either:
if (phraseArray[i] != phraseArray[j])
Or
newPhrase = phraseArray[i];
Will fail, specially newPhrase = phraseArray[i];, because here you're trying to replace newPhrase an array, for a character phrase[i]. Basically your solution won't work. So what you can do is do what #Travis suggested, basically change your arrays from String[]to char[], then:
char[] phraseArray = phrase.ToCharArray();
Or Instead of using arrays you can just use another string to filter your phrase. The first string being your phrase and the second would be the string you'd add your non repeated characters to. basically this:
Console.WriteLine("Entrez une phrase SVP!!");
string phrase = Console.ReadLine();
string newPhrase = "";
// loop through each character in phrase
for (int i = 0; i < phrase.Length; i++) {
// We check if the character of phrease is within our newPhrase, if it isn't we add it, otherwise do nothing
if (newPhrase.IndexOf(phrase[i]) == -1)
newPhrase += phrase[i]; // here we add it to newPhrase
}
Console.WriteLine(newPhrase);
Don't forget to read the comments in the code.
Edit:
Based on the comments and suggestions given I implemented a similar solution:
Console.WriteLine("Entrez une phrase SVP!!");
char[] phrase = Console.ReadLine().ToCharArray();
char[] newPhrase = new char[phrase.Length];
int index = 0;
// loop through each character in phrase
for (int i = 0; i < phrase.Length; i++) {
// We check if the character of phrease is within our newPhrase, if it isn't we add it, otherwise do nothing
if (Array.IndexOf(newPhrase, phrase[i]) == -1)
newPhrase[index++] = phrase[i]; // here we add it to newPhrase
}
Console.WriteLine(newPhrase);
I'm facing a problem while developing an application.
Basically,
I have a fixed string, let's say "IHaveADream"
I now want to user to insert another string, for my purpose of a fixed length, and then concatenate every character of the fixed string with every character of the string inserted by the user.
e.g.
The user inserts "ByeBye"
then the output would be:
"IBHyaevBeyAeDream".
How to accomplish this?
I have tried with String.Concat and String.Join, inside a for statement, with no luck.
One memory-efficient option is to use a string builder, since both the original string and the user input could potentially be rather large. As mentioned by Kris, you can initialize your StringBuilder capacity to the combined length of both strings.
void Main()
{
var start = "IHaveADream";
var input = "ByeBye";
var sb = new StringBuilder(start.Length + input.Length);
for (int i = 0; i < start.Length; i++)
{
sb.Append(start[i]);
if (input.Length >= i + 1)
sb.Append(input[i]);
}
sb.ToString().Dump();
}
This only safely accounts for the input string being shorter or equal in length to the starting string. If you had a longer input string, you'd want to take the longer length as the end point for your for loop iteration and check that each array index is not out of bounds.
void Main()
{
var start = "IHaveADream";
var input = "ByeByeByeByeBye";
var sb = new StringBuilder(start.Length + input.Length);
var length = start.Length >= input.Length ? start.Length : input.Length;
for (int i = 0; i < length; i++)
{
if (start.Length >= i + 1)
sb.Append(start[i]);
if (input.Length >= i + 1)
sb.Append(input[i]);
}
sb.ToString().Dump();
}
You can create an array of characters and then re-combine them in the order you want.
char[] chars1 = "IHaveADream".ToCharArray();
char[] chars2 = "ByeBye".ToCharArray();
// you can create a custom algorithm to handle
// different size strings.
char[] c = new char[17];
c[0] = chars1[0];
c[1] = chars2[0];
...
c[13] = chars1[10];
string s = new string(c);
var firstString = "Ihaveadream";
var secondString = "ByeBye";
var stringBuilder = new StringBuilder();
for (int i = 0; i< firstString.Length; i++) {
stringBuilder .Append(str[i]);
if (i < secondString.Length) {
stringBuilder .Append(secondStr[i]);
}
}
var result = stringBuilder.ToString();
If you don't care much about memory usage or perfomance you can just use:
public static string concatStrings(string value, string value2)
{
string result = "";
int i = 0;
for (i = 0; i < Math.Max(value.Length, value2.Length) ; i++)
{
if (i < value.Length) result += value[i].ToString();
if (i < value2.Length) result += value2[i].ToString();
}
return result;
}
Usage:
string conststr = "IHaveADream";
string input = "ByeBye";
var result = ConcatStrings(conststr, input);
Console.WriteLine(result);
Output: IBHyaevBeyAeDream
P.S.
Just checked perfomance of both methods (with strBuilder and simple cancatenation) and it appears to be that both of this methods take same time to execute (if you have just one operation). The main reason for it is that string builder take considerable time to initialize while with use of concatenation we don't need that.
But in case if you have to process something like 1500 strings then it's different story and string builder is more of an option.
For 100 000 method executions it showed 85 (str buld) vs 22 (concat) ms respectively.
My Code
I'm beginning programming with C# and have a question:
I have a string of character like abcdef123456789. But the string is too long, therefore I want to add : automatically, after the second, fourth, six .... symbol.
How can I do that?
There is no built in method that does something like that. You just have to put the separators in there by looping through the string.
You can loop though the characters and put them in a StringBuilder, adding a colon at every other character:
string input = "abcdef123456789";
StringBuilder builder = new StringBuilder();
int cnt = 0;
foreach (char c in input) {
if (cnt == 2) {
builder.Append(':');
cnt = 0;
}
builder.Append(c);
cnt++;
}
string output = builder.ToString();
You could try this approach. I've attempted to make it as readable as possible, so hopefully it makes sense to you.
var s = "abcdef123456789";
var charsChanged = new List<char>();
for (var i = 0; i < s.Length; i++)
{
charsChanged.Add(s[i]);
var evenCharacter = i % 2 != 0;
var atEndOfString = i == s.Length - 1;
if (evenCharacter && !atEndOfString)
{
charsChanged.Add(':');
}
}
var updatedString = string.Concat(charsChanged));
updatedString will equal ab:cd:ef:12:34:56:78:9.
This approach makes use of the modulus operator (%) to determine if we're at an even or odd character. For more examples, check this out.
You can use a StringBuilder and do something like this:
string sourceStr = "123456789";
StringBuilder s = new StringBuilder();
foreach(char c in sourceStr){
s.append(c);
s.append(":");
}
How to delete every 2nd character in a string?
For example:
3030313535333635 -> 00155365
3030303336313435 -> 00036145
3032323437353530 -> 02247550
The strings are always 16-characters long and the result is always 8 characters long - and the character that is being removed is always a '3' - Don't ask why however - I did not dream up this crazy source data.
Try this to get the every other character from the string:-
var s = string.Join<char>("", str.Where((ch, index) => (index % 2) != 0));
String input = "3030313535333635";
String result = "";
for(int i = 1; i < 16; i +=2 )
{
result += input[i];
}
You can use this well-known class System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary :)
string str = "3030313535333635";
var hex = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(str);
var newstr = Encoding.ASCII.GetString(hex.Value);
Using a StringBuilder to create a string will save resources
string input = "3030313535333635";
var sb = new StringBuilder(8); // Specify capacity = 8
for (int i = 1; i < 16; i += 2) {
sb.Append(input[i]);
}
string result = sb.ToString();
Code in Java Language
String input= "3030313535333635"
String output="";
for(int i=1;i<input.length();i=i+2)
{
output+=input.charAt(i).toString();
}
System.out.println(output);
I have a string variable with value
"abcdefghijklmnop".
Now I want to split the string into string array with, say, three characters (the last array element may contain fewer) in each array element from the right end.
I.e.,
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
What is the easiest and simplest way to do this?? (Both Visual Basic and C# code is welcome)?
Here's a solution:
var input = "abcdefghijklmnop";
var result = new List<string>();
int incompleteGroupLength = input.Length % 3;
if (incompleteGroupLength > 0)
result.Add(input.Substring(0, incompleteGroupLength));
for (int i = incompleteGroupLength; i < input.Length; i+=3)
{
result.Add(input.Substring(i, 3));
}
It gives the expected output of:
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
Here's something that works - wrapped up into a string extension function.
namespace System
{
public static class StringExts
{
public static IEnumerable<string> ReverseCut(this string txt, int cutSize)
{
int first = txt.Length % cutSize;
int taken = 0;
string nextResult = new String(txt.Take(first).ToArray());
taken += first;
do
{
if (nextResult.Length > 0)
yield return nextResult;
nextResult = new String(txt.Skip(taken).Take(cutSize).ToArray());
taken += cutSize;
} while (nextResult.Length == cutSize);
}
}
}
Usage:
textBox2.Text = "";
var txt = textBox1.Text;
foreach (string s in txt.ReverseCut(3))
textBox2.Text += s + "\r\n";
Regex time!!
Regex rx = new Regex("^(.{1,2})??(.{3})*$");
var matches = rx.Matches("abcdefgh");
var pieces = matches[0].Groups[1].Captures.OfType<Capture>().Select(p => p.Value).Concat(matches[0].Groups[2].Captures.OfType<Capture>().Select(p => p.Value)).ToArray();
pieces will contain:
"ab"
"cde"
"fgh"
(Please, don't use this code! It is only an example of what can happen when you use a regular expression + LINQ.)
Well... here is yet another way I arrived at:
private string[] splitIntoAry(string str)
{
string[] temp = new string[(int)Math.Ceiling((double)str.Length / 3)];
while (str != string.Empty)
{
temp[(int)Math.Ceiling((double)str.Length / 3) - 1] = str.Substring(str.Length - Math.Min(str.Length, 3));
str = str.Substring(0, str.Length - Math.Min(str.Length, 3));
}
return temp;
}