How do you convert a string to ascii to binary in C#? - c#

A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the following code sample:
void ToBinary(char* str)
{
char* tempstr;
int k = 0;
tempstr = new char[90];
while (str[k] != '\0')
{
itoa((int)str[k], tempstr, 2);
cout << "\n" << tempstr;
k++;
}
delete[] tempstr;
}
So I guess my question is how do I get an equivalent to the itoa function in C#? Or if there is not one how could I achieve the same effect?

This is very easy to do with C#.
var str = "Hello world";
With LINQ
foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
Console.WriteLine(letter);
}
Pre-LINQ
foreach (char letter in str.ToCharArray())
{
Console.WriteLine(Convert.ToString(letter, 2));
}

Use an ASCIIEncoding class and call GetBytes passing the string.

It's not clear precisely what you want, but here's what I think you want:
return Convert.ToString(int.Parse(str), 2); // "5" --> "101"
This isn't what the C++ code does. For that, I suggest:
string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
foreach(string s in binaryDigits) Console.WriteLine(s);

Thanks, this is great!! I've used it to encode query strings...
protected void Page_Load(object sender, EventArgs e)
{
string page = "";
int counter = 0;
foreach (string s in Request.QueryString.AllKeys)
{
if (s != Request.QueryString.Keys[0])
{
page += s;
page += "=" + BinaryCodec.encode(Request.QueryString[counter]);
}
else
{
page += Request.QueryString[0];
}
if (!page.Contains('?'))
{
page += "?";
}
else
{
page += "&";
}
counter++;
}
page = page.TrimEnd('?');
page = page.TrimEnd('&');
Response.Redirect(page);
}
public class BinaryCodec
{
public static string encode(string ascii)
{
if (ascii == null)
{
return null;
}
else
{
char[] arrChars = ascii.ToCharArray();
string binary = "";
string divider = ".";
foreach (char ch in arrChars)
{
binary += Convert.ToString(Convert.ToInt32(ch), 2) + divider;
}
return binary;
}
}
public static string decode(string binary)
{
if (binary == null)
{
return null;
}
else
{
try
{
string[] arrStrings = binary.Trim('.').Split('.');
string ascii = "";
foreach (string s in arrStrings)
{
ascii += Convert.ToChar(Convert.ToInt32(s, 2));
}
return ascii;
}
catch (FormatException)
{
throw new FormatException("SECURITY ALERT! You cannot access a page by entering its URL.");
}
}
}
}

Here's an extension function:
public static string ToBinary(this string data, bool formatBits = false)
{
char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
int index = 0;
for (int i = 0; i < data.Length; i++)
{
string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
for (int j = 0; j < 8; j++)
{
buffer[index] = binary[j];
index++;
}
if (formatBits && i < (data.Length - 1))
{
buffer[index] = ' ';
index++;
}
}
return new string(buffer);
}
You can use it like:
Console.WriteLine("Testing".ToBinary());
which outputs:
01010100011001010111001101110100011010010110111001100111
and if you add 'true' as a parameter, it will automatically separate each binary sequence.

Related

Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program

This is the code I'll try. But I got wrong output. Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program.
namespace Uncensor
{
class Program
{
// "*h*s *s v*ry *tr*ng*", "Tiiesae" ➜ "This is very strange"
static string uncensor(string str,string s)
{
string s1 = "";
int i, j;
if (str.Contains("*"))
{
for (i = 0; i < str.Length; i++)
{
if (str[i] == '*')
{
for (j = 0; j < s.Length; j++)
{
s1 = str.Replace(str[i], s[j]);
}
}
}
return s1;
}
else
{
return str;
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter string:");
string str = Console.ReadLine();
Console.WriteLine("Enter string to be replaced by * :");
string s = Console.ReadLine();
string original_text= uncensor(str, s);
Console.WriteLine(original_text);
Console.Read();
}
}
}
This is easy with linq:
string a = "*h*s *s v*ry *tr*ng*";
string b = "Tiiesae";
int index = 0;
string c = new string(a.Select(x => x == '*' ? b[index++] : x).ToArray());
public string solve(string str, string s)
{
int index = 0;
for(int i = 0; i < str.Length; ++i)
{
if(str[i] == '*') {
str[i] = s[index];
++index;
}
return str;
}

merge two strings based on index of character

I am trying to write a code to merge two string based on index of character.For e.g-If we have two string "abc" and "defg",I want a string output1(merging all even character of both strings)="adcf" and another string output2="beg" (remaining all words).
What I tried-
class Program
{
static void Main(string[] args)
{
string a= "First";
string b= "MiddleName";
string newstring = "";
string newstring1 = "";
int length = b.Length;
for (int l = 0; l < length; l=l+1)
{
if(l%2==0)
{
newstring = newstring + a[l].ToString() + b[l].ToString();
}
if (l % 2 == 1)
{
newstring1 = newstring1 + a[l].ToString() + b[l].ToString();
}
}
Console.ReadLine();
}
}
But then in this case it will give outside the bound array exception.Any better way to do this?
Thanks
I suggest extracting a method where you should solve the generalized problem of merging two strings taking each step characters from them starting from offset:
private static String Merge(String left, String right, int step, int offset) {
StringBuilder sb = new StringBuilder();
if (null == left)
left = ""; // or throw exception
if (null == right)
right = ""; // or throw exception
for (int i = offset; i < Math.Max(left.Length, right.Length); i += step) {
//DONE: do not forget to check if you can get a character
if (i < left.Length)
sb.Append(left[i]);
//DONE: do not forget to check if you can get a character
if (i < right.Length)
sb.Append(right[i]);
}
return sb.ToString();
}
And so you can put it
String a = "abc";
String b = "defg";
// adcf
String output1 = Merge(a, b, 2, 0);
// beg
String output2 = Merge(a, b, 2, 1);
it happens because B has longer words than A. So when its iteration is bigger than A' length, it will cause an error.
so you need to check whether A has that much word, before adding it
IF B' length always greater than A, then you can use bellow code
class Program
{
static void Main(string[] args)
{
string a= "First";
string b= "MiddleName";
string newstring = "";
string newstring1 = "";
int length = b.Length;
for (int l = 0; l < length; l=l+1)
{
if(l%2==0)
{
if(a.Length > l)
{newstring += a[l].ToString();}
newstring += b[l].ToString();
}
if (l % 2 == 1)
{
if(a.Length > l)
{newstring1 += a[l].ToString();}
newstring1 += b[l].ToString();
}
}
Console.ReadLine();
}
}
for (int l = 0; l < b.length && l < a.length; l++)
{
if(l%2==0)
{
newstring += a[l]+ b[l];
}
if (l % 2 == 1)
{
newstring1 += a[l] + b[l];
}
}

String find and replace

I have a string like
string text="~aaa~bbb~ccc~bbbddd";
The input value will be : bbb
So in the above string i should remove the value "~bbb"
The resulting string should be
text="~aaa~ccc~bbbddd";
I'm not sure what are you wanna do but if i've got it you can do this :
private string ReplaceFirstOccurrence(string Source, string Find, string Replace)
{
int Place = Source.IndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
var result =ReplaceFirstOccurrence(text,"~"+input,"");
One way would be:
string text = "~aaa~bbb~ccc~bbbddd";
string newStr = string.Join("~", text.Split('~').Where(r => r != "bbb"));
But if performance is the consideration then consider some other solution
You can use the regular expression #"\bMYWORDTOREPLACE\b" in c# this would be...
using System.Text.RegularExpressions;
myString = Regex.Replace(myString, #"\bbbb\b", "", RegexOptions.IgnoreCase);
This should do the trick:
string searchValue = "bbb";
text = text.Replace(String.Format("~{0}~", searchValue), "~");
Be sure to search for the ending ~ character as well, otherwise you will also replace part of ~bbbddd.
Like this
string str = "~rajeev~ravi";
string strRemove = "rajeev";
string strNew =str.Replace("~"+strRemove ,"");
public static string Replace(this String str, char[] chars, string replacement)
{
StringBuilder output = new StringBuilder(str.Length);
bool replace = false;
if (chars.Length - 1 < 1)
{
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
replace = false;
// int val = Regex.Matches(ch.ToString(), #"[a-zA-Z]").Count;
for (int j = 0; j < chars.Length; j++)
{
if (chars[j] == c)
{
replace = true;
break;
}
}
if (replace)
output.Append(replacement);
else
output.Append(c);
}
}
else
{
int j = 0;
int truecount = 0;
char c1 = '\0';
for (int k = 0; k < str.Length; k++)
{
c1 = str[k];
if (chars[j] == c1)
{
replace = true;
truecount ++;
}
else
{
truecount = 0;
replace = false;
j = 0;
}
if(truecount>0)
{
j++;
}
if (j > chars.Length-1)
{
j = 0;
}
if (truecount == chars.Length)
{
output.Remove(output.Length - chars.Length+1, chars.Length-1);
// output.Remove(4, 2);
if (replace)
output.Append(replacement);
else
output.Append(c1);
}
else
{
output.Append(c1);
}
}
}
return output.ToString();
}
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string word = (Console.ReadLine());
Console.WriteLine("Enter a word to find");
string find = (Console.ReadLine());
Console.WriteLine("Enter a word to Replace");
string Rep = (Console.ReadLine());
Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
Console.ReadLine();
}
}
This is an old question, but my solution is to create extension function for string.
Like ".ReplaceFirst" Java method.
You need to create static class like Helper and inside that class create static extension function:
public static class Helpers
{
public static string ReplaceFirst(this String str, string find, string replace)
{
int place = str.IndexOf(find);
if (place < 0)
{
return str;
}
//return str.Substring(0, place) + replace + str.Substring(place + find.Length);
return str.Remove(place, find.Length).Insert(place, replace);
}
}
Usage is same like .Replace method...
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", ""); //text="~aaa~ccc~bbbddd"
or more
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", "").ReplaceFirst("~bbb", ""); //text="~aaa~cccddd"
Well, you could do something like this.
(You only need to input 'bbb')
string text = "~aaa~bbb~ccc~bbbddd";
string input = "bbb";
string output = text.Replace("~" + input + "~", "~");
Console.WriteLine(output);
Output: ~aaa~ccc~bbbddd

Extract Field Names and max lengths from a text file using C#

I have a file that is a SQL Server result set saved as a text file.
Here is a sample of what the file looks like:
RWS_DMP_ID RV1_DMP_NUM CUS_NAME
3192 3957 THE ACME COMPANY
3192 3957 THE ACME COMPANY
3192 3957 THE ACME COMPANY
I want to create a C# program that reads this file and creates the following table of data:
Field MaxSize
----- -------
RWS_DMP_ID 17
RV1_DMP_NUM 17
CUS_NAME 42
This is a list of the field names and their max length. The max length is the beginning of the field to the space right before the beginning of the next field.
By the way I don't care about code performance. This is seldom used file processing utility.
I solved this with the following code:
objFile = new StreamReader(strPath + strFileName);
strLine = objFile.ReadLine();
intLineCnt = 0;
while (strLine != null)
{
intLineCnt++;
if (intLineCnt <= 3)
{
if (intLineCnt == 1)
{
strWords = SplitWords(strLine);
intNumberOfFields = strWords.Length;
foreach (char c in strLine)
{
if (bolNewField == true)
{
bolFieldEnd = false;
bolNewField = false;
}
if (bolFieldEnd == false)
{
if (c == ' ')
{
bolFieldEnd = true;
}
}
else
{
if (c != ' ')
{
if (intFieldCnt < strWords.Length)
{
strProcessedData[intFieldCnt, 0] = strWords[intFieldCnt];
strProcessedData[intFieldCnt, 1] = (intCharCnt - 1).ToString();
}
intFieldCnt++;
intCharCnt = 1;
bolNewField = true;
}
}
if (bolNewField == false)
{
intCharCnt++;
}
}
strProcessedData[intFieldCnt, 0] = strWords[intFieldCnt];
strProcessedData[intFieldCnt, 1] = intCharCnt.ToString();
}
else if (intLineCnt == 3)
{
intLine2Cnt= 0;
intTotalLength = 0;
while(intLine2Cnt < intNumberOfFields)
{
intSize = Convert.ToInt32(strProcessedData[intLine2Cnt, 1]);
if (intSize + intTotalLength > strLine.Length)
{
intSize = strLine.Length - intTotalLength;
}
strField = strLine.Substring(intTotalLength, intSize);
strField = strField.Trim();
strProcessedData[intLine2Cnt, intLineCnt - 1] = strField;
intTotalLength = intTotalLength + intSize + 1;
intLine2Cnt++;
}
}
}
strLine = objFile.ReadLine();
}`enter code here`
I'm aware that this code is a complete hack job. I'm looking for a better way to solve this problem.
Is there a better way to solve this problem?
THanks
I'm not sure how memory efficient this is, but I think it's a bit cleaner (assuming your fields are tab-delimited):
var COL_DELIMITER = new[] { '\t' };
string[] lines = File.ReadAllLines(strPath + strFileName);
// read the field names from the first line
var fields = lines[0].Split(COL_DELIMITER, StringSplitOptions.RemoveEmptyEntries).ToList();
// get a 2-D array of the columns (excluding the header row)
string[][] columnsArray = lines.Skip(1).Select(l => l.Split(COL_DELIMITER)).ToArray();
// dictionary of columns with max length
var max = new Dictionary<string, int>();
// for each field, select all columns, and take the max string length
foreach (var field in fields)
{
max.Add(field, columnsArray.Select(row => row[fields.IndexOf(field)]).Max(col => col.Trim().Length));
}
// output per requirment
Console.WriteLine(string.Join(Environment.NewLine,
max.Keys.Select(field => field + " " + max[field])
));
void MaximumWidth(StreamReader reader)
{
string[] columns = null;
int[] maxWidth = null;
string line;
while ((line = reader.ReadLine()) != null)
{
string[] cols = line.Split('\t');
if (columns == null)
{
columns = cols;
maxWidth = new int[cols.Length];
}
else
{
for (int i = 0; i < columns.Length; i++)
{
int width = cols[i].Length;
if (maxWidth[i] < width)
{
maxWidth[i] = width;
}
}
}
}
// ...
}
Here is what I came up with. The big takeaway is to use the IndexOf string function.
class Program
{
static void Main(string[] args)
{
String strFilePath;
String strLine;
Int32 intMaxLineSize;
strFilePath = [File path and name];
StreamReader objFile= null;
objFile = new StreamReader(strFilePath);
intMaxLineSize = File.ReadAllLines(strFilePath).Max(line => line.Length);
//Get the first line
strLine = objFile.ReadLine();
GetFieldNameAndFieldLengh(strLine, intMaxLineSize);
Console.WriteLine("Press <enter> to continue.");
Console.ReadLine();
}
public static void GetFieldNameAndFieldLengh(String strLine, Int32 intMaxSize)
{
Int32 x;
string[] fields = null;
string[,] strFieldSizes = null;
Int32 intFieldSize;
fields = SplitWords(strLine);
strFieldSizes = new String[fields.Length, 2];
x = 0;
foreach (string strField in fields)
{
if (x < fields.Length - 1)
{
intFieldSize = strLine.IndexOf(fields[x + 1]) - strLine.IndexOf(fields[x]);
}
else
{
intFieldSize = intMaxSize - strLine.IndexOf(fields[x]);
}
strFieldSizes[x, 0] = fields[x];
strFieldSizes[x, 1] = intFieldSize.ToString();
x++;
}
Console.ReadLine();
}
static string[] SplitWords(string s)
{
return Regex.Split(s, #"\W+");
}
}

csharp method that choose every second character from the word

I need a method that returns every other character in a string starting with the first character. For example, a method call with ("Java-language") returns "Jv-agae."
private static void NewMethod(string word)
{
// here comes the code
}
var str = "Java-language";
var xx = new string(str.Where((ch, index) => index % 2 == 0).ToArray());
Console.WriteLine(xx);
Or this one:
var xx = string.Join<char>("", str.Where((ch, index) => (index & 1) == 0));
probably little different then everybody else: :-)
protected static IEnumerable<char> EverySecondChar(string word)
{
for(int i = 0; i < word.Length; i += 2)
yield return word[i];
}
string result = new string(EverySecondChar("Java-language").ToArray());
Here is my suggestion for you:
private string TakeEverySecondChar(string input)
{
var result = string.Empty;
for (int i = 0; i < input.Length; i+=2)
{
result += input.Substring(i, 1);
}
return result;
}
Console.Clear();
string Lang = "Java-language";
string[] LangArr = new string[Lang.Length];
char LangChar;
for (int i = 0; i < Lang.Length; i++)
{
LangChar = Lang[i];
LangArr[i] = LangChar.ToString();
}
for (int i = 0; i < LangArr.Length; i++)
{
Console.Write(LangArr[i]);
i++;
}
Console.ReadLine();
public String strip2ndchar(string text)
{
string final="";
int i = 0;
foreach (char a in text.ToCharArray())
{
if (i % 2 == 0)
final += a;
i++;
}
return final;
}

Categories