I tried to split a String into a parts array and combine them at the end into a result String.
But while I tested a little bit, I get a message.
By pressing convert_click:
"NullRefenceException was unhandeled"
Object reference not set to an instance of an object.
Here the main code:
public string []parts { get; set; }
public string inputStr { get; set; }
private void inputText_TextChanged(object sender, EventArgs e)
{
String inputStr = inputText.ToString();
//example
//inputStr = "984, fenceshit2, 0, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1";
}
private void convert_Click(object sender, EventArgs e)
{
String creObj = "CreateObject(";
String result;
String[] parts = inputStr.Split(new char[] { ',' });
result = creObj +
parts[0] + "," +
parts[2] + "," +
parts[3] + "," +
//...up to "parts[10"
");";
outputText.Text = result;
//output(should be in this case):
//"CreateObject(984, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1);"
}
//If I need to creat a code line in the main Designer.cs, please let me know.
I just want to split a String and combine them in the end into 1 string and send this into a text box.
If someone wants the sourcecode, pm me.
Because you are assigning inputText.toString() to local inputStr. Inside function inputText_TextChanged, just write
inputStr = inputText.Text;
You are declaring a local copy of input string, when you really want to be assigning to the public one.
Instead of
String inputStr = inputText.ToString();
Just do this:
inputStr = inputText.ToString();
Related
The following is a simple program that takes an input string, reverses the order of the characters and prints the result.
There are two methods here (//method 1 and //method 2) that both produce the same result. I am just utterly lost in how they do this.
namespace HelperMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The Name Game");
Console.Write("What's your first name? ");
string firstName = Console.ReadLine();
Console.Write("What's your last name? ");
string lastName = Console.ReadLine();
Console.Write("In what city were you born? ");
string city = Console.ReadLine();
DisplayResult(
ReverseString(firstName),
ReverseString(lastName),
ReverseString(city));
Console.WriteLine();
DisplayResult(
ReverseString(firstName) + " " +
ReverseString(lastName) + " " +
ReverseString(city));
Console.ReadLine();
}
//accepts input peramaters variable = string name = message
private static string ReverseString(string message)
{//inputs characters, concatenates and returns string
char[] messageArray = message.ToCharArray();
Array.Reverse(messageArray);
return String.Concat(messageArray);
}
private static void DisplayResult( //method 1
string reversedFirstName,
string reversedLastName,
string reversedCity)
{
Console.Write("Results: ");
Console.Write(String.Format("{0} {1} {2}",
reversedFirstName,
reversedLastName,
reversedCity));
}
private static void DisplayResult(string message) //method 2
{
Console.Write("Results: ");
Console.Write(message);
}
}
}
how can you declare string reversedFirstName and have it filled with the string?
Perhaps it might give you insight with this code: broken down into parts
String revFirst = ReverseString(firstName); // get reverse of firstName
String revLast = ReverseString(lastName); // get reverse of lastName
String revCity = ReverseString(city); // get reverse of city
// use string format to combine the reversed strings creating a new one
String mystring = String.Format("{0} {1} {2}", revFirst, revLast, revCity);
DisplayResult(mystring); // now display that new string using method 2
Note that the net result of mystring is the same as combining the strings manually as is done calling the other method, with the ReverseString(firstName) + " " + ... code
I'm trying to write some code for unity in c#. I am having a problem wring \n into a List. Heres my code.
public static List<string> ChatHeads = null;
public void Start()
{
ChatHeads = new List<string>();
}
void Update()
{
ChatBoxMessage.text = GetChatHead();
}
string GetChatHead()
{
return string.Join(System.Environment.NewLine, ChatHeads.ToArray());
}
public void MainFunc()
{
string FinalMessage = "";
if (FinalMessage.Length >= 82 || !.inWorld)
{
FinalMessage = Message + "\n";
ChatHeads.Add(FinalMessage);
}
else
{
FinalMessage = "[" + username + "] " + MainWorld.ChatTag + Message + "\n";
ChatHeads.Add(FinalMessage);
}
}
The issue is GetChatHead() only returns the first array string if \n isnt the last part of the string. code works fine as long as the \n appears but it NEVER does always disappears.
thanks.
Pic to List array, No \n at end of any lines.
[2
Solved. Apparently Encoding.Default.GetString() wont allow you to add anything to the string.
Message = Encoding.Default.GetString(packet.ReadBytes((int)Length));
No Good
Message = packet.ReadString();
Worked.
How can we read a text file column by column.
Check my new code: I can read the data row-wise using text.split (' ')
But how can be the file read as column wise? Lets assume that a file contains number of rows and columns but I was able to read the data/value horizontally. The code you see that below that's what I could execute!
SEE THE CODE BELOW:-
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = "";
text = textBox1.Text;
string[] arr = text.Split(' ');
textBox2.Text = arr[5];
textBox3.Text = arr[8];
}
private void button3_Click(object sender, EventArgs e)
{
string file_name = "c:\\Excel\\count.txt";
string txtline = "";
System.IO.StreamReader objreader;
objreader = new System.IO.StreamReader(file_name);
do
{
txtline = txtline + objreader.ReadLine() + "\r\n";
txtline = txtline + objreader.ReadToEnd() + "";
this.textBox1.Text = "subzihut";
}
while (objreader.Peek() != -1);
textBox1.Text = txtline;
objreader.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = textBox2.Text + " " + textBox3.Text;
}
}
}
A textfile contains a sequence of characters, delimited by newline characters and probably other characters which are used as delimiters (usually a comma or a semiciolon).
When you read a file you simply read this stream of characters. There are helper functions which read such a file line-by-line (using the newline character as a delimiter).
In plain .Net there are no methods which read column-by-column.
So you should:
read the file line by line
split each line into fields/columns using string.Split() at the separator character(s)
access only the columns of interest
You can simply read the file line by line, splitt the lines and do whatever you want.
var lines = File.ReadLines(#"c:\yourfile.txt");
foreach(var line in lines)
{
var values = line.Split(' ');
}
public string getColumnString(int columnNumber){
string[] lines = System.IO.ReadAllLines(#"C:\inputfile.txt");
string stringTobeDisplayed = string.Empty;
foreach(string line in lines) {
if(columnNumber == -1){ //when column number is sent as -1 then read full line
stringTobeDisplayed += line +"\n"
}
else{ //else read only the column required
string [] words = line.Split();
stringTobeDisplayed += word[columnNumber] +"\n"
}
}
return stringTobeDisplayed;
}
Maybe this will help you:
public static void ReadFile(string path)
{
List<string> Col1 = new List<string>();
List<string> Col2 = new List<string>();
List<string> Col3 = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (sr.EndOfStream)
{
string header = sr.ReadLine();
var values = header.Split(' ');
Col1.Add(values[0]);
Col2.Add(values[1]);
Col3.Add(values[2]);
}
}
}
It's true that sometimes you just don't know where to start. Here are some pointers.
You'll have to read the whole file in, probably using something like a StreamReader.
You can parse the first row into column names. Use StreamReader.ReadLine() to get the first line and then do some simple string parsing on it.
You'll want to create some kind of class/object to store and access your data.
Once you have column names, continue to parse the following lines into the proper arrays.
Some here's a rough idea
using(StreamReader sr = new StreamReadeR("C:\\my\\file\\location\\text.csv"))
{
string header = sr.ReadLine();
List<string> HeaderColumns = new List<string>(header.split(" ", StringSplitOptions.RemoveEmptyEntires));
myModelClass.Header = HeaderColumns;
etc...
You might also consider making some kind of dictionary to access columns by header name and index.
I have a program that I need to have a config file with value to be
displayed in my program. Inside my text file I have Wireless = 1
& Cradle = 2.
In my program I will have a label populate the release number only and not the other
characters.
private string searchFile(String path, String searchText)
{
string regex=#"(?i)(?<="+searchText+#"\s*=\s*)\d+";
return Regex.Match(File.ReadAllText(path),regex).Value;//version number
}
This is what I tried and it gives the correct output
string s="Wireless = 1 Cradle = 2";
Regex.Match(s,#"(?i)(?<=Wireless\s*=\s*)\d+").Value;//1
public static string match;
public static string ReadAllText(string path)
{
using (var r = new System.IO.StreamReader(path))
{
return r.ReadToEnd();
}
}
private string Wireless(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label1.Text = match;
return match;
}
private string Cradle(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label2.Text = match;
return match;
}
private void button1_Click(object sender, EventArgs e)
{
Wireless(#"\Storage Card\changelog.txt","Wireless");
Cradle(#"\Storage Card\changelog.txt", "Cradle");
}
I have an app that goes in, replaces "invalid" chars (as defined by my Regex) with a blankspace. I want it so that if there are 2 or more blank spaces in the filename, to trim one. For example:
Deal A & B.txt after my app runs, would be renamed to Deal A B.txt (3 spaces b/w A and B). What i want is really this: Deal A B.txt (one space between A and B).
I'm trying to determine how to do this--i suppose my app will have to run through all filenames at least once to replace invalid chars and then run through filenames again to get rid of extraneous whitespace.
Can anybody help me with this?
Here is my code currently for replacing the invalid chars:
public partial class CleanNames : Form
{
public CleanNames()
{
InitializeComponent();
}
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
StreamWriter errors = new StreamWriter(#"S:\Testing\Errors.txt", true);
var filesCount = new Dictionary<string, int>();
dataGridView1.Rows.Clear();
try
{
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = sanitizedFileName;
dataGridView1.Rows.Add(clean);
System.IO.File.Move(files2, sanitized);
}
else
{
if (filesCount.ContainsKey(sanitized))
{
filesCount[sanitized]++;
}
else
{
filesCount.Add(sanitized, 1);
}
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(sanitized),
filesCount[sanitized].ToString(),
System.IO.Path.GetExtension(sanitized));
string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sanitized), newFileName);
System.IO.File.Move(files2, newFilePath);
sanitized = newFileName;
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}
}
}
catch (Exception e)
{
errors.Write(e);
}
}
private void SanitizeFileNames_Load(object sender, EventArgs e)
{ }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
The problem is, that not all files after a rename will have the same amount of blankspaces. As in, i could have Deal A&B.txt which after a rename would become Deal A B.txt (1 space b/w A and B--this is fine). But i will also have files that are like: Deal A & B & C.txt which after a rename is: Deal A B C.txt (3 spaces between A,B and C--not acceptable).
Does anybody have any ideas/code for how to accomplish this?
Do the local equivalent of:
s/\s+/ /g;
Just add a space to your regPattern. Any collection of invalid characters and spaces will be replaced with a single space. You may waste a little bit of time replacing a space with a space, but on the other hand you won't need a second string manipulation call.
Does this help?
var regex = new System.Text.RegularExpressions.Regex("\\s{2,}");
var result = regex.Replace("Some text with a lot of spaces, and 2\t\ttabs.", " ");
Console.WriteLine(result);
output is:
Some text with a lot of spaces, and 2 tabs.
It just replaces any sequence of 2 or more whitespace characters with a single space...
Edit:
To clarify, I would just perform this regex right after your existing one:
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
Regex regExPattern2 = new Regex(#"\s{2,}");
and:
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement); // clean up whitespace
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
I hope that makes more sense.
you can perform another regex replace after your first one
#" +" -> " "
As Fosco said, with formatting:
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
// || || |
After you're done sanitizing it your way, simply replace 2 spaces with 1 space, while 2 spaces exist in the string.
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
I think that's the right syntax...