Unity string to binary converter output error - c#

I've been trying to make a simple string to the binary converter in unity using C#. The code is converting it well but the problem I am getting is that when outputting, the output is only the last letter typed.
For example, when "Hello" is typed I want it to display
01001000 01100101 01101100 01101100 01101111
But I am only getting the o conversion which is 01101111
Here is my code in unity c#:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextInput : MonoBehaviour
{
InputField textInput;
InputField.SubmitEvent se;
public Text output;
// Use this for initialization
void Start()
{
textInput = gameObject.GetComponent<InputField>();
se = new InputField.SubmitEvent();
se.AddListener(SubmitInput);
textInput.onEndEdit = se;
}
private void SubmitInput(string arg0)
{
string currentText = output.text;
string newtext = currentText + "\n" + arg0;
foreach (char c in newtext)
output.text = newtext + " in binary is " + "\n" + (Convert.ToString(c, 2).PadLeft(8, '0'));
textInput.text = "";
textInput.ActivateInputField();
}
}

You're overwriting the output.text every time you loop through a character in newtext.
Currently you are doing :
output.text = newtext + " in binary is " + binary thing 1
output.text = newtext + " in binary is " + binary thing 2
You should be using the += operator, however this will create a string that prints
:
Hello in binary is "value for h" Hello in binary is "value for e"
etc.
You should create a string variable that you add to for the binary value, and then add that to output.text after the foreach loop.
private void SubmitInput(string arg0)
{
string currentText = output.text;
string newtext = currentText + "\n" + arg0;
string binaryText; //This string will contain the Binary Data
foreach (char c in newtext)
{
binaryText += (Convert.ToString(c, 2).PadLeft(8, '0')); //Add that character's binary data to the binary string
}
output.text = newtext + " in binary is " + "\n" + binaryText;//Print the binary string after the speicifed text
textInput.text = "";
textInput.ActivateInputField();
}

Hello your code works correctly for me, you are overwriting your data use: output.text +=
Also verify that your text field is multiline or try removing the
\n
The BestFit option in the Text component can also help improve visualization

To get the desired output change your codes as follows:
string binaryText = "";
foreach (char c in newtext)
binaryText += (Convert.ToString(c, 2).PadLeft(8, '0')) + " ";
output.text = newtext + " in binary is " + "\n" + binaryText;
If you use LINQ you can simplify it:
var binaryText = string.Join(" ", newtext.ToList().Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));

Related

Prevent last key in string to have a comma

Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);

Setting a string from one destination to another

I want to include the string "oldSummary" in the second richtextbox, however all of the summary's functionality belongs to a streamRead after opening a file. Is there a way for that when btn1 button is clicked, it will display the oldSummary string? At the moment it's blank due to it's global string set to "" but I want it to display the oldSummary string set in the mnuOpen button.
string oldSummary = "";
private void mnuOpen_Click(object sender, EventArgs e)
{
//Load up file code which I remove for this example but goes here…
//Add data from text file to rich text box
richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
//Read lines of text in text file
string textLine = "";
int lineCount = 0;
System.IO.StreamReader txtReader;
txtReader = new System.IO.StreamReader(Chosen_File);
do
{
textLine = textLine + txtReader.ReadLine() + " ";
lineCount++;
}
//Read line until there is no more characters
while (txtReader.Peek() != -1);
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = textLine.Length - lineCount;
string divider = "------------------------";
//Unprocessed Summary
string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
txtReader.Close();
}
private void btn1_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
wholeText = oldSummary + copyText;
richTextBox2.Text = wholeText;
}
If you want to use the global variable oldSummary then do not redeclare one with the same name inside the menu open event handler, just use the global one
//Unprocessed Summary
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
Try replacing:
string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
with:
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
so that you assign the value to the class field used in btn1_Click.

Replace closest instance of a word

I have a string like this:
“I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”
I want to insert <strong> around the "a" in "a diplomatic", but nowhere else.
What I have as input is diplomatic from a previous function, and I wan't to add <strong>to the closest instance of "a".
Right now, of course when I use .Replace("a", "<strong>a</strong>"), every single instance of "a" receives the <strong>-treatment, but is there any way to apply this to just to one I want?
Edit
The string and word/char ("a" in the case above) could be anything, as I'm looping through a lot of these, so the solution has to be dynamic.
var stringyourusing = "";
var letter = "";
var regex = new Regex(Regex.Escape(letter));
var newText = regex.Replace(stringyourusing , "<strong>letter</strong>", 1);
Would this suffice?
string MakeStrongBefore(string strong, string before, string s)
{
return s.Replace(strong + " " + subject, "<strong>" + strong + "</strong> " + before);
}
Used like this:
string s = “I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”;
string bolded = MakeStrongBefore("a", "diplomatic", s);
Try this:
public string BoldBeforeString(string source, string bolded,
int boldBeforePosition)
{
string beforeSelected = source.Substring(0, boldBeforePosition).TrimEnd();
int testedWordStartIndex = beforeSelected.LastIndexOf(' ') + 1;
string boldedString;
if (beforeSelected.Substring(testedWordStartIndex).Equals(bolded))
{
boldedString = source.Substring(0, testedWordStartIndex) +
"<strong>" + bolded + "</strong>" +
source.Substring(testedWordStartIndex + bolded.Length);
}
else
{
boldedString = source;
}
return boldedString;
}
string phrase = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
string boldedPhrase = BoldBeforeString(phrase, "a", 41);
Hei!
I've tested this and it works:
String replaced = Regex.Replace(
"I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.",
#"(a) diplomatic",
match => "<strong>" + match.Result("$1") + "</strong>");
So to make it a general function:
public static String StrongReplace(String sentence, String toStrong, String wordAfterStrong)
{
return Regex.Replace(
sentence,
#"("+Regex.Escape(toStrong)+") " + Regex.Escape(wordAfterStrong),
match => "<strong>" + match.Result("$1") + "</strong>");
}
Usage:
String sentence = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
String replaced = StrongReplace(sentence, "a", "diplomatic");
edit:
considering your other comments, this is a function for placing strong tags around each word surrounding the search word:
public static String StrongReplace(String sentence, String word)
{
return Regex.Replace(
sentence,
#"(\w+) " + Regex.Escape(word) + #" (\w+)",
match => "<strong>" + match.Result("$1") + "</strong> " + word + " <strong>" + match.Result("$2") + "</strong>");
}

Can only display array by iterating through a for loop

Hello I am trying to make a C# program that downloads files but I am having trouble with the array.
I have it split up the text for downloading and put it into a 2 level jagged array (string[][]).
Now I split up the rows up text by the | char so each line will be formatted like so:
{filename}|{filedescription}|{filehttppath}|{previewimagepath}|{length}|{source}
when I use short test text to put it into a text box it displays fine in the text box.
IE: a string like test|test|test|test|test|test
but if I put in a real string that I would actually be using for the program to DL files the only way I get the string to display is to iterate through it with a for or foreach loop. If I try to access the data with the index I get an index missing error. (IE array[0])
So this is the code that gets the array to display:
public Form2(string[][] textList, string path)
{
InitializeComponent();
textBox1.Text = textBox1.Text + path + Environment.NewLine;
WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
for(int j=0;j<i.Length;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
}
}
And then this is the code that gives an index missing error:
public Form2(string[][] textList, string path)
{
InitializeComponent();
textBox1.Text = textBox1.Text + path + Environment.NewLine;
WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
textBox1.Text = textBox1.Text + i[0] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[1] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[2] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[3] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[4] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[5] + Environment.NewLine;
}
}
Any help is this is apreciated I don't see why I can access they data through a for loop but not directly it just doesn't make any sense to me.
Also, here is the code that generates the array:
public String[][] finalList(string[] FileList)
{
String[][] FinalArray = new String[FileList.Length][];
for (int i = 0; i<FinalArray.Length;i++)
{
string[] fileStuff = FileList[i].Split(new char[] {'|'});
FinalArray[i] = fileStuff;
}
return FinalArray;
}
In your first example you are using the actual length of each inner array to do the concatenation. In your second example you are hard coded to the same length yet you said in the intro it was a jagged array.
Can you show what your input text looks like?
you are not doing the same concatenation in first and second example so the resulting stings are very different.
first = "\r\n Crazy Video\r\n\\\\newline\r\nThis Video is absolutly crazy!\r\n\\\\newline\r\nhtt://fakeurl.fake/vidfolder/video.flv\r\n\\\\newline\r\nhtt://fakeurl.fake/imgfolder/img.j‌​pg\r\n\\\\newline\r\n300\r\n\\\\newline\r\nhtt://fakeurl.fake \r\n\\\\newline\r\n"
second = "\r\n Crazy Video\r\nThis Video is absolutly crazy!\r\nhtt://fakeurl.fake/vidfolder/video.flv\r\nhtt://fakeurl.fake/imgfolder/img.j‌​pg\r\n300\r\nhtt://fakeurl.fake \r\n"
using System;
using NUnit.Framework;
namespace ClassLibrary5
{
public class Class1
{
[Test]
public void test()
{
var temp = new[]
{
" Crazy Video|This Video is absolutly crazy!|htt://fakeurl.fake/vidfolder/video.flv|htt://fakeurl.fake/imgfolder/img.j‌​pg|300|htt://fakeurl.fake "
};
var final = finalList(temp);
var first = Form1(final, "path");
var second = Form2(final, "path");
Assert.IsTrue(first.CompareTo(second) == 0);
}
public string Form1(string[][] textList, string path)
{
string textString = path + Environment.NewLine;
foreach (string[] i in textList)
{
for (int j = 0; j < i.Length; j++)
{
textString = textString + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
}
return textString;
}
public string Form2(string[][] textList, string path)
{
string textString = path + Environment.NewLine;
foreach (string[] i in textList)
{
textString = textString + i[0] + Environment.NewLine;
textString = textString + i[1] + Environment.NewLine;
textString = textString + i[2] + Environment.NewLine;
textString = textString + i[3] + Environment.NewLine;
textString = textString + i[4] + Environment.NewLine;
textString = textString + i[5] + Environment.NewLine;
}
return textString;
}
public String[][] finalList(string[] FileList)
{
String[][] FinalArray = new String[FileList.Length][];
for (int i = 0; i < FinalArray.Length; i++)
{
string[] fileStuff = FileList[i].Split(new char[] {'|'});
FinalArray[i] = fileStuff;
}
return FinalArray;
}
}
}
Are you sure each String[] in string[][] textList has 6 elements?
Try to replace:
for(int j=0;j<i.Length;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
with:
for(int j=0;j<6;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
And see if you get the same result. Your middle one has different logic than your first one. To troubleshoot, first make the logic the same, and then continue troubleshooting from there.

Adding a newline into a string in C#

I have a string.
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
I need to add a newline after every occurence of "#" symbol in the string.
My Output should be like this
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
Use Environment.NewLine whenever you want in any string. An example:
string text = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
text = text.Replace("#", "#" + System.Environment.NewLine);
You can add a new line character after the # symbol like so:
string newString = oldString.Replace("#", "#\n");
You can also use the NewLine property in the Environment Class (I think it is Environment).
The previous answers come close, but to meet the actual requirement that the # symbol stay close, you'd want that to be str.Replace("#", "#" + System.Environment.NewLine). That will keep the # symbol and add the appropriate newline character(s) for the current platform.
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("#", "#" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
A simple string replace will do the job. Take a look at the example program below:
using System;
namespace NewLineThingy
{
class Program
{
static void Main(string[] args)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + Environment.NewLine);
Console.WriteLine(str);
Console.ReadKey();
}
}
}
as others have said new line char will give you a new line in a text file in windows.
try the following:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
#"C:\test.txt",
"fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#",
"#"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
var result = strToProcess.Replace("#", "# \r\n");
Console.WriteLine(result);
Output
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", Environment.NewLine);
richTextBox1.Text = str;
Based on your replies to everyone else, something like this is what you're looking for.
string file = #"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
string[] lines = strToProcess.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string line in lines)
{
writer.WriteLine(line + "#");
}
}
Change your string as mentioned below.
string strToProcess = "fkdfdsfdflkdkfk"+ System.Environment.NewLine +" dfsdfjk72388389"+ System.Environment.NewLine +"kdkfkdfkkl"+ System.Environment.NewLine +"jkdjkfjd"+ System.Environment.NewLine +"jjjk"+ System.Environment.NewLine;
You could also use string[] something = text.Split('#'). Make sure you use single quotes to surround the "#" to store it as a char type.
This will store the characters up to and including each "#" as individual words in the array. You can then output each (element + System.Environment.NewLine) using a for loop or write it to a text file using System.IO.File.WriteAllLines([file path + name and extension], [array name]). If the specified file doesn't exist in that location it will be automatically created.
protected void Button1_Click(object sender, EventArgs e)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + "<br/>");
Response.Write(str);
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
strToProcess.Replace("#", Environment.NewLine);
Console.WriteLine(strToProcess);
}
}

Categories

Resources