Convert Multi-Dimensional Array to String and Back - c#

I have a 2D array that I need to be able to convert to a string representation and back to array format. I would like to create a generci method that will handle any array 1d, 2d, 3d etc. so I can reuse the method in future.
What is the best way of going about this?
string[,] _array = new string[_helpTextItemNames.Count, 2];

If you do not care to much about the structure of the string then the SoapFormatter is an option. Here is a quick and dirty example. Not pretty but it might work for you.
public static class Helpers
{
public static string ObjectToString(Array ar)
{
using (MemoryStream ms = new MemoryStream())
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(ms, ar);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public static object ObjectFromString(string s)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
SoapFormatter formatter = new SoapFormatter();
return formatter.Deserialize(ms) as Array;
}
}
public static T ObjectFromString<T>(string s)
{
return (T)Helpers.ObjectFromString(s);
}
}
These helpers can be used to transform any Serializable object to a string, including arrays, as long as the elements of the array are serializable.
// Serialize a 1 dimensional array to a string format
char[] ar = { '1', '2', '3' };
Console.WriteLine(Helpers.ObjectToString(ar));
// Serialize a 2 dimensional array to a string format
char[,] ar2 = {{ '1', '2', '3' },{ 'a', 'b', 'c' }};
Console.WriteLine(Helpers.ObjectToString(ar2));
// Deserialize an array from the string format
char[,] ar3 = Helpers.ObjectFromString(Helpers.ObjectToString(ar2)) as char[,];
char[,] ar4 = Helpers.ObjectFromString<char[,]>(Helpers.ObjectToString(ar2));

If you want to determain your own format, the hard part is just walking a rectangular array because Array.GetValue and Array.SetValue expect a specific form. Here is StringFromArray, I'll leave ArrayFromString as an exercise (it's just the reverse with a little parsing). Note that the code below only works on rectangular arrays. If you want to support jagged arrays, that's completely different, but at least much simpler. You can tell if an array is jagged by checking array.GetType() for Array. It also doesn't support arrays whos lower-bounds is anything other than zero. For C# that doesn't mean anything, but it does mean that it may not work as a general library to be used from other languages. This can be fixed, but it's not worth the price of admission IMO. [deleted explative about non-zero-based arrays]
The format used here is simple:
[num dimensions]:[length dimension #1]:[length dimension #2]:[...]:[[string length]:string value][[string length]:string value][...]
static string StringFromArray(Array array)
{
int rank = array.Rank;
int[] lengths = new int[rank];
StringBuilder sb = new StringBuilder();
sb.Append(array.Rank.ToString());
sb.Append(':');
for (int dimension = 0; dimension < rank; dimension++)
{
if (array.GetLowerBound(dimension) != 0)
throw new NotSupportedException("Only zero-indexed arrays are supported.");
int length = array.GetLength(dimension);
lengths[dimension] = length;
sb.Append(length);
sb.Append(':');
}
int[] indices = new int[rank];
bool notDone = true;
NextRank:
while (notDone)
{
notDone = false;
string valueString = (array.GetValue(indices) ?? String.Empty).ToString();
sb.Append(valueString.Length);
sb.Append(':');
sb.Append(valueString);
for (int j = rank - 1; j > -1; j--)
{
if (indices[j] < (lengths[j] - 1))
{
indices[j]++;
if (j < (rank - 1))
{
for (int m = j + 1; m < rank; m++)
indices[m] = 0;
}
notDone = true;
goto NextRank;
}
}
}
return sb.ToString();
}

As I know, you have a 2d array[n cols x n rows]. And you want convert it to string, and after that you'd like to convert this string back in to a 2d array. I have an idea as follow:
//The first method is convert matrix to string
private void Matrix_to_String()
{
String myStr = "";
Int numRow, numCol;//number of rows and columns of the Matrix
for (int i = 0; i < numRow; i++)
{
for (int j = 0; j < numCol; j++)
{
//In case you want display this string on a textbox in a form
//a b c d . . . .
//e f g h . . . .
//i j k l . . . .
//m n o p . . . .
//. . . . . . . .
textbox.Text = textbox.Text + " " + Matrix[i,j];
if ((j == numCol-1) && (i != numRow-1))
{
textbox.Text = textbox.Text + Environment.NewLine;
}
}
}
myStr = textbox.text;
myStr = myStr.Replace(" ", String.Empty);
myStr = myStr.Replace(Environment.NewLine,String.Empty);
}
//and the second method convert string back into 2d array
private void String_to_Matrix()
{
int currentPosition = 0;
Int numRow, numCol;//number of rows and columns of the Matrix
string Str2 = textbox.Text;
Str2 = Str2 .Replace(" ", string.Empty);
Str2 = Str2 .Replace(Environment.NewLine, string.Empty);
for (int k = 0; k < numRow && currentPosition < Str2 .Length; k++)
{
for (int l = 0; l < numCol && currentPosition < Str2 .Length; l++)
{
char chr = Str2 [currentPosition];
Matrix[k, l] = chr ;
currentPosition++;
}
}
}
Hope this help!

Related

Converting string[] to double[]

I have a text file that is being read in and then stored in a string[] which I then then convert into an int[], my bubblesort then should sort it but it doesn't because the values from the text files are decimals. So my question is how do I convert either the string[] or int[] to something that can accept decimal values, such as a double[] if there is such a thing. Thanks.
Code:
string[] sh1OpenData = File.ReadAllLines("SH1_Open.txt");
...
else if(input2.ToLower() == "open") //----
{
int[] intSh1OpenData = new int[sh1OpenData.Length];
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToInt32(sh1OpenData[x]);
}
Console.WriteLine("\n");
Console.WriteLine("Unsorted");
for (int i = 0; i < intSh1OpenData.Length; i++)
{
Console.Write(intSh1OpenData[i] + " ");
Console.WriteLine(" ");
}
int temp = 0;
for (int write = 0; write < intSh1OpenData.Length; write++)
{
for (int sort = 0; sort < intSh1OpenData.Length - 1; sort++)
{
if (intSh1OpenData[sort] > intSh1OpenData[sort + 1])
{
temp = intSh1OpenData[sort + 1];
intSh1OpenData[sort + 1] = intSh1OpenData[sort];
intSh1OpenData[sort] = temp;
}
}
}
Console.WriteLine("\n\n\nSORTED");
for (int i = 0; i < intSh1OpenData.Length; i++)
Console.Write(intSh1OpenData[i] + "\n");
}
You should not be using int to do comparisons on string. Use String.Compare(return 0 if equal, -1 if less than, or 1 if greater than) or List.Sort() to sort string array
Pretty simple with LINQ
var asDouble = sh1OpenData.Select(x => Double.Parse(x)).OrderBy(x => x).ToArray();
This will give you a sorted (ascending order) array of Double.
Note: this assumes that all of sh1OpenData can be parsed as a Double, and will throw an exception if not.
The only changes that you will need to make are listed below:
double[] intSh1OpenData = new double[sh1OpenData.Length]; // double[] instead of int[]
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToDouble(sh1OpenData[x]); // Convert to Double
}
also change the declaration of your temp variable to double temp;
Something that you could read through since you mentioned that you are new to programming:
C# Sort Arrays and Lists Examples
MSDN: List.Sort Method

Intersect two lists and return the similarity with the preserved order of the original first string value

I'm facing a problem I don't even know what to search in Google/Stack Overflow.
So comment if you feel the need for further explanation, questions.
Basically I want to intersect two lists and return the similarity with the preserved order of the original first string value.
Example:
I have two strings, that I convert to a CharArray.
I want to Intersect these two arrays and return the values that are similar, including/with the order of the first string (s1).
As you can see the first string contains E15 (in that specific order), and so does the seconds one.
So these two strings will return : { 'E', '1', '5' }
string s1 = "E15QD(A)";
string s2 = "NHE15H";
The problem I am facing is that if i replace "s2" with:
string s2 = "NQE18H" // Will return {'Q', 'E', '1' }
My operation will return : {'Q', 'E', '1' }
The result should be : {'E', '1' } because Q don't follow the letter 1
Currently my operation is not the greatest effort, because i don't know which methods to use in .NET to be able to do this.
Current code:
List<char> cA1 = s1.ToList();
List<char> cA2 = s2.ToList();
var result = cA1.Where(x => cA2.Contains(x)).ToList();
Feel free to help me out, pointers in the right direction is acceptable as well as a full solution.
This is a "longest common substring" problem.
You can use this extension to get all substrings lazily:
public static class StringExtensions
{
public static IEnumerable<string> GetSubstrings(this string str)
{
if (string.IsNullOrEmpty(str))
throw new ArgumentException("str must not be null or empty", "str");
for (int c = 0; c < str.Length - 1; c++)
{
for (int cc = 1; c + cc <= str.Length; cc++)
{
yield return str.Substring(c, cc);
}
}
}
}
Then it's easy and readable with this LINQ query:
string longestIntersection = "E15QD(A)".GetSubstrings()
.Intersect("NQE18H".GetSubstrings())
.OrderByDescending(s => s.Length)
.FirstOrDefault(); // E1
Enumerable.Intersect is also quite efficient since it's using a set. One note: if one both strings is larger than the other then it's more efficient(in terms of memory) to use it first:
longString.GetSubstrings().Intersect(shortString.GetSubstrings())
I think this should do it:
string similar = null;
for (int i = 0; i < s1.Length; i++)
{
string s = s1.Substring(0, i + 1);
if (s2.Contains(s))
{
similar = s;
}
}
char[] result = similar.ToCharArray();
#TimSchmelter provided the link to this answer in the comments of the original post.
public int LongestCommonSubstring(string str1, string str2, out string sequence)
{
sequence = string.Empty;
if (String.IsNullOrEmpty(str1) || String.IsNullOrEmpty(str2))
return 0;
int[,] num = new int[str1.Length, str2.Length];
int maxlen = 0;
int lastSubsBegin = 0;
StringBuilder sequenceBuilder = new StringBuilder();
for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
if (str1[i] != str2[j])
num[i, j] = 0;
else
{
if ((i == 0) || (j == 0))
num[i, j] = 1;
else
num[i, j] = 1 + num[i - 1, j - 1];
if (num[i, j] > maxlen)
{
maxlen = num[i, j];
int thisSubsBegin = i - num[i, j] + 1;
if (lastSubsBegin == thisSubsBegin)
{//if the current LCS is the same as the last time this block ran
sequenceBuilder.Append(str1[i]);
}
else //this block resets the string builder if a different LCS is found
{
lastSubsBegin = thisSubsBegin;
sequenceBuilder.Length = 0; //clear it
sequenceBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin));
}
}
}
}
}
sequence = sequenceBuilder.ToString();
return maxlen;
}

Programming C# array multiplication

I have a function that takes a string and returns a string. In it, I convert the string into an integer array and later try to multiply every other number like this:
private string addEveryOther(string x)
{
int[] d = x.Select(n => Convert.ToInt32(n)).ToArray();
for(int i = 0; i < 10; i++)
{
d[i] = d[i] * 2;
MessageBox.Show(d[i].ToString()); //Display the result?
i++;
}
// And later returning a string:
StringBuilder g = new StringBuilder();
foreach (int n in d)
{
g.Append(Convert.ToChar(n));
}
return g.ToString();
}
This works with addition, but not with multiplication as it returns strange values. If I input "3434343434" i expect it to return "6464646464". Now it returns: "f4f4f4f4f4" and I don't know why? Any suggestions how to go about it?
Based on the discussions above, I suppose your method should use ToString instead of Convert.ToChar.
private string addEveryOther(string x)
{
int[] d = x.Select(n => Convert.ToInt32(n.ToString())).ToArray();
for(int i = 0; i < d.Length; i += 2)
{
d[i] = d[i] * 2;
MessageBox.Show(d[i].ToString()); //Display the result?
}
// And later returning a string:
return String.Concat(d.Select(n => n.ToString()));
}
EDIT: Using #Kirill's Concat solution and #Reniuz comment in the addEveryOther method should hopefully solve the problem.
As I wrote in comment Convert.ToInt32(char)
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
So when you converting "0" result will be 48, when "1" result 50 and so on.
Here's changed code:
private string addEveryOther(string x)
{
//1. Convert string to int, not char to int
int[] d = x.Select(n => Convert.ToInt32(n.ToString())).ToArray();
//2. start from second number
for (int i = 1; i < 10; i++)
{
d[i] = d[i] * 2;
MessageBox.Show(d[i].ToString()); //Display the result?
i++;
}
string s = d.ToString();
// And later returning a string:
StringBuilder g = new StringBuilder();
foreach (int n in d)
{
//3. Convert int to string, not to char
g.Append(n.ToString());
}
return g.ToString();
}
Try this:
int[] d = x.Select(n => int.Parse(n.ToString())).ToArray();
for(int i = 0; i < 10; i++)
{
d[i] = (i%2 == 0? d[i] * 2 : d[i]);
}
StringBuilder g = new StringBuilder();
foreach (int n in d)
{
g.Append(n);
}
return g.ToString();
hope it helps
When you use
Convert.ToInt32(n.ToString())
There is redundant conversion. I think the simplest way is
var d = x.Select(n => Char.IsDigit(n) ? n - '0' : 0).ToArray();

How to Sort 2D Array in C#

I've read lots of posts about sorting a 2D array but I still can't master it so I was wondering if anyone can offer me some advice...
I have an aray which lists letters and quantity (I'm doing a frequency anaysis on a piece of text). I've read this data into a rectangle array and need to order it by highest frequency first. Here's my code so far:
//create 2D array to contain ascii code and quantities
int[,] letterFrequency = new int[26, 2];
//fill in 2D array with ascaii code and quantities
while (asciiNo <= 90)
{
while ((encryptedText.Length - 1) > counter)
{
if (asciiNo == (int)encryptedText[index])
{
letterCount++;
}
counter++;
index++;
}
letterFrequency[(storeCount), (0)] = (char)(storeCount+66);
letterFrequency[(storeCount), (1)] = letterCount;
storeCount++;
counter=0;
index=0;
letterCount = 0;
asciiNo++;
}
You are using a 2D array to represent 2 separate vectors - the symbols and the counts. Instead, use 2 separate arrays. Array.Sort has an overload that takes 2 arrays, and sorts on one array, but applies the changes to both, achieving what you want.
This would also allow you to use a char[] for the characters rather than int[]:
char[] symbols = ...
int[] counts = ...
...load the data...
Array.Sort(counts, symbols);
// all done!
At this
point, the counts have been ordered, and the symbols will still match index-by-index with the count they relate to.
You can wrap letter-count pair in a struct and use linq methods to manipulate data:
struct LetterCount {
public char Letter { get; set; }
public int Count { get; set; }
}
Sorting by count will look like this:
List<LetterCount> counts = new List<LetterCount>();
//filling the counts
counts = counts.OrderBy(lc => lc.Count).ToList();
public static void Sort2DArray<T>(T[,] matrix)
{
var numb = new T[matrix.GetLength(0) * matrix.GetLength(1)];
int i = 0;
foreach (var n in matrix)
{
numb[i] = n;
i++;
}
Array.Sort(numb);
int k = 0;
for (i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = numb[k];
k++;
}
}
}
Alternative approach:
var counts = new Dictionary<char,int>();
foreach(char c in text) {
int count;
counts.TryGetValue(c, out count);
counts[c] = count + 1;
}
var sorted = counts.OrderByDescending(kvp => kvp.Value).ToArray();
foreach(var pair in sorted) {
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
(untested)
In this case I'd choose to make use of KeyValuePair<TKey, TValue> and instead use something like this:
//create 2D array to contain ascii code and quantities
KeyValuePair<char, int>[] letterFrequency = new KeyValuePair<char, int>[26];
//fill in 2D array with ascaii code and quantities
while (asciiNo <= 90)
{
while ((encryptedText.Length - 1) > counter)
{
if (asciiNo == (int)encryptedText[index])
{
letterCount++;
}
counter++;
index++;
}
letterFrequency[storeCount] = new KeyValuePair<char, int>((char)(storeCount+66), letterCount);
storeCount++;
counter=0;
index=0;
letterCount = 0;
asciiNo++;
}
Then use Array.Sort:
Array.Sort(letterFrequency, (i1, i2) => i2.Value.CompareTo(i1.Value));
This'll sort a two dimension array, the bool specifies if it's sorted on the second dimension, but default it sorts on the first dimension.
void SortDoubleDimension<T>(T[,] array, bool bySecond = false)
{
int length = array.GetLength(0);
T[] dim1 = new T[length];
T[] dim2 = new T[length];
for (int i = 0; i < length; i++)
{
dim1[i] = array[i, 0];
dim2[i] = array[i, 1];
}
if (bySecond) Array.Sort(dim2, dim1);
else Array.Sort(dim1, dim2);
for (int i = 0; i < length; i++)
{
array[i, 0] = dim1[i];
array[i, 1] = dim2[i];
}
}
Why are you storing the character? You can infer it from the array index and do not need to store it! Use a one-dimensional array instead.
string encryptedText = "Test".ToUpper();
int[] frequency = new int[26];
foreach (char ch in encryptedText) {
int charCode = ch - 'A';
frequency[charCode]++;
}
var query = frequency
.Select((count, index) => new { Letter = (char)(index + 'A'), Count = count })
.Where(f => f.Count != 0)
.OrderByDescending(f => f.Count)
.ThenBy(f => f.Letter);
foreach (var f in query) {
Console.WriteLine("Frequency of {0} is {1}", f.Letter, f.Count);
}

Function that generates strings according to input

I need a C# function that takes 2 strings as an input and return an array of all possible combinations of strings.
private string[] FunctionName(string string1, string string2)
{
//code
}
The strings input will be in the following format:
string1: basement
string2: a*fa
Now what I need is all combinations of possible strings using the characters in String2 (ignoring the * symbols), and keeping them in the same character position like this:
baaement, baaefent, baaefena, basefent, basemena, etc.
EDIT:
This is not homework. I need this function for a piece of a program I am doing.
The following is the code I have so far but it has some bugs.
static List<string> combinations = new List<string>();
static void Main(string[] args)
{
//include trimming of input string
string FoundRes = "incoming";
string AltRes = "*2*45*78";
List<int> loc = new List<int>();
string word = "";
for (int i = 0; i < AltRes.Length; i++)
{
if (AltRes[i] != '*')
{
loc.Add(i);
word += AltRes[i];
}
}
generate(word);
string[] aaa = InsertSymbol(FoundRes, loc.ToArray(), AltRes, combinations);
Console.WriteLine("input string: " + FoundRes);
Console.WriteLine("Substitute string: " + AltRes);
Console.WriteLine("============Output============");
for (int j = 0; j < aaa.Length; j++)
{
Console.WriteLine(aaa[j]);
}
Console.ReadKey();
}//
private static void generate(string word)
{
// Add this word to combination results set
if (!combinations.Contains(word))
combinations.Add(word);
// If the word has only one character, break the recursion
if (word.Length == 1)
{
if (!combinations.Contains(word))
combinations.Add(word);
return;
}
// Go through every position of the word
for (int i = 0; i < word.Length; i++)
{
// Remove the character at the current position
// call this method with the String
generate(word.Substring(0, i) + word.Substring(i + 1));
}
}//
private static string[] InsertSymbol(string orig, int[] loc, string alternative, List<string> Chars)
{
List<string> CombinationsList = new List<string>();
string temp = "";
for (int i = 0; i < Chars.Count; i++)
{
temp = orig;
for (int j = 0; j < Chars[i].Length; j++)
{
string token = Chars[i];
if (alternative.IndexOf(token[j]) == loc[j])
{
temp = temp.Remove(loc[j], 1);
temp = temp.Insert(loc[j], token[j].ToString());
// int pos = sourceSubst.IndexOf(token[j]);
// sourceSubst = sourceSubst.Remove(pos, 1);
// sourceSubst = sourceSubst.Insert(pos, ".");
}
else
{
temp = temp.Remove(alternative.IndexOf(token[j]), 1);
temp = temp.Insert(alternative.IndexOf(token[j]), token[j].ToString());
}
}
CombinationsList.Add(temp);
}
return CombinationsList.ToArray();
}//
It does sound like homework. As a suggestion, I would ignore the first parameter and focus on getting all possible permutations of the second string. What's turned off, what's turned on, etc. From that list, you can easily come up with a method of swapping out characters of the first string.
On that note, I'm in the uncomfortable position of having a function ready to go but not wanting to post it because of the homework implication. I'd sure love for somebody to review it, though! And technically, there's two functions involved because I just happened to already have a generic function to generate subsets lying around.
Edit: OP says it isn't homework, so here is what I came up with. It has been refactored a bit since the claim of two functions, and I'm more than open to criticism.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string original = "phenomenal";
string pattern = "*xo**q*t**";
string[] replacements = StringUtility.GetReplacementStrings(original, pattern, true);
foreach (string replacement in replacements)
Console.WriteLine(replacement);
Console.Read();
}
public static class StringUtility
{
public static string[] GetReplacementStrings(string original, string pattern, bool includeOriginal)
{
// pattern and original might not be same length
int maxIndex = Math.Max(original.Length, pattern.Length);
List<int> positions = GetPatternPositions(pattern, maxIndex, '*');
List<int[]> subsets = ArrayUtility.CreateSubsets(positions.ToArray());
List<string> replacements = GenerateReplacements(original, pattern, subsets);
if (includeOriginal)
replacements.Insert(0, original);
return replacements.ToArray();
}
private static List<string> GenerateReplacements(string original, string pattern, List<int[]> subsets)
{
List<string> replacements = new List<string>();
char[] temp = new char[original.Length];
foreach (int[] subset in subsets)
{
original.CopyTo(0, temp, 0, original.Length);
foreach (int index in subset)
{
temp[index] = pattern[index];
}
replacements.Add(new string(temp));
}
return replacements;
}
private static List<int> GetPatternPositions(string pattern, int maxIndex, char excludeCharacter)
{
List<int> positions = new List<int>();
for (int i = 0; i < maxIndex; i++)
{
if (pattern[i] != excludeCharacter)
positions.Add(i);
}
return positions;
}
}
public static class ArrayUtility
{
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
}
}
since it's hopw work I'd only suggest some way to solve the problem rather than writing the code.
if you loop the second parameter every time you hit a letter you'll have to options either use the letter from the first argument or the letter from the second. collect all these optins together with the index. keep a list of the parts from the first argument that will never change. iterate thorugh those two lists to created all the possible permutations
Decimal to Binary converted code is stolon copied from here.
static void Main()
{
string string1 = "basement";
string string2 = "**a*f**a";
string[] result = GetCombinations(string1, string2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static string[] GetCombinations(string string1, string string2)
{
var list = new List<List<char>> { new List<char>(), new List<char>() };
var cl = new List<char>();
List<string> result = new List<string>();
for (int i = 0; i < string1.Length; i++)
{
if (string2[i] == '*')
{
cl.Add(string1[i]);
}
else
{
list[0].Add(string1[i]);
list[1].Add(string2[i]);
}
}
int l = list[0].Count;
for (int i = 0; i < (Int64)Math.Pow(2.0,l); i++)
{
string s = ToBinary(i, l);
string ss = "";
int x = 0;
int y = 0;
for (int I = 0; I < string1.Length; I++)
{
if (string2[I] == '*')
{
ss += cl[x].ToString();
x++;
}
else
{
ss += (list[int.Parse(s[y].ToString())][y]);
y++;
}
}
result.Add(ss);
}
return result.ToArray<string>();
}
public static string ToBinary(Int64 Decimal, int width)
{
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
var d = width - BinaryResult.Length;
if (d != 0) for (int i = 0; i < d; i++) BinaryResult = "0" + BinaryResult;
return BinaryResult;
}
which password cracker do you want to program? :)
how about
if string2 contains '*'
foreach(char ch in string1)
replace first * with ch,
execute FunctionName
else
print string2

Categories

Resources