I try to detect quotes in a loaded text file but it is not working. I have tried with '"' and '\"' without success. Any suggestion? thanks
void read()
{
txt = File.ReadAllText("txt/txttst");
for(int i=0;i<txt.Length;i++)
{
if(txt[i]=='"')
{
Debug.Log("Quotes at "+i);
}
}
}
How about this
string[] lines = File.ReadAllLines(#"txt/txttst");
for (int i=0;i<lines.Length;i++)
{
string line = lines[i];
// ASCII Code of Quotes is 34
var bytes = Encoding.UTF8.GetBytes(line.ToCharArray()).ToList();
if(bytes.Count(b=> b.ToString()=="34")>0)
Console.WriteLine("\"" + "at line " + (i + 1));
}
This is how you can do it, please see the code and screenshot below. Hope it helps.
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
string txt = File.ReadAllText(#"C:\Users\Public\TestFolder\test.txt");
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\test.txt");
var reg = new Regex("\"");
Console.WriteLine("Contents of test.txt are; ");
foreach (string line in lines)
{
Console.WriteLine(line);
var matches = reg.Matches(line);
foreach (var item in matches)
{
Console.WriteLine("Quotes at "+ ((System.Text.RegularExpressions.Capture)item).Index);
}
}
}
}
}
Ok I found the problem, my text editor did a subtle auto-correct from " to “ . Cheers.
Related
I am trying to create a simple minifier because I am unsatisfied with the tools online. I have made a console application, but the problem is that nothing is removed, even though I split the text and remove /n and /t characters.
I've tried different methods of removing the whitespace.
static string restrictedSymbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,0123456789";
...
static void Compress(string command)
{
string[] commandParts = command.Split(' ');
string text = String.Empty;
try
{
using (StreamReader sr = new StreamReader(commandParts[1]))
{
text = sr.ReadToEnd();
text.Replace("\n", "");
text.Replace("\t", "");
string formattedText = text;
string[] splitText = text.Split(' ');
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitText.Length - 1; i++)
{
splitText[i].TrimStart();
StringBuilder tSB = new StringBuilder(splitText[i]);
if (splitText[i].Length > 1 && splitText[i + 1].Length > 1)
{
int textLength = splitText[i].Length - 1;
if (restrictedSymbols.Contains(splitText[i + 1][0]) && restrictedSymbols.Contains(splitText[i][textLength]))
{
tSB.Append(" ");
}
}
sb.Append(tSB.ToString());
}
sb.Append(splitText[splitText.Length - 1]);
text = sb.ToString();
Console.WriteLine(text);
}
} catch (IOException e)
{
Console.WriteLine(e.ToString());
}
if (text != String.Empty)
{
try
{
using (StreamWriter stream = File.CreateText(commandParts[2] + commandParts[3]))
{
stream.Write(text);
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Process Complete...");
GetCommand();
}
It should print output a minified file, but it just outputs the same exact file that I put in.
Ignoring any other problem, Replace by it self does nothing
Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with
another specified Unicode character or String.
So basically you are ignoring any changes by not keeping the return value
At minimum you will need to do something like this
text = text.Replace("\n", "");
You're replacing the characters, but then doing nothing with it.
Your code should be:
text = text.Replace("\n", "");
text = text.Replace("\t", "");
I've seen a lot of answers about using Trim for whitespace, but I need to trim everything after the first space as in " ". I'll post the section of code that I am talking about first and then below it I'll post the whole thing. I also want to know how to get a "tab" space in between the file and line variables in the same location. Here is the snippet of code I'm talking about.
var files = from file in Directory.EnumerateFiles(filePath, "*.FCJ", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains(".FCM")
select Path.GetFileName(file + line);
foreach (var f in files)
{
lbMerges.Items.Add(f);
}
The variable "line" comes out as Text ~Space~ More Text. I want to eliminate the second section "More Text". I also would like to know how to get my ouput in a listview to show a tab in between the file name and the line that is read. Here is the entire code in case you need it.
private void rbActive_CheckedChanged(object sender, EventArgs e)
{
if (rbActive.Checked == true)
{
cbFullPath.Enabled = false;
cbFullPath.Visible = false;
lbMerges.Items.Clear();
lbPCL.Items.Clear();
string filePath = textBox1.Text;
try
{
var files = from file in Directory.EnumerateFiles(filePath, "*.FCJ", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains(".FCM")
select Path.GetFileName(file + line);
foreach (var f in files)
{
lbMerges.Items.Add(f);
}
}
catch (UnauthorizedAccessException UAEx)
{
MessageBox.Show(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
MessageBox.Show(PathEx.Message);
}
}
else
{
cbFullPath.Enabled = true;
cbFullPath.Visible = true;
}
}
Here you go:
void Main()
{
string test = "text some more text";
string result = test.Substring(0,test.IndexOf(" "));
// prints "text"
Console.WriteLine(result);
}
void Main()
{
string column2 = "Put me at column 15";
List<string> test = new List<string>() {"text some more text",
"longtext somemore text",
"t some more text" };
List<string> result = test
.Select(s => s.Substring(0,s.IndexOf(" ")).PadRight(15) + column2)
.ToList();
// output
// text Put me at column 15
// longtext Put me at column 15
// t Put me at column 15
foreach(string s in result)
Console.WriteLine(s);
}
public void replaceText(string messageText)
{
int counter = 1;
string csvFile = "textwords.csv";
string[] words = messageText.Split(' ');
char csvSeparator = ',';
foreach (string word in words)
{
foreach (string line in File.ReadLines(csvFile))
{
foreach (string value in line.Replace("\"", "").Split('\r', '\n', csvSeparator))
if (value.Trim() == word.Trim()) // case sensitive
{
messageText = Regex.Replace(messageText, value, string.Empty);
messageText = messageText.Insert(counter, " " + line);
}
}
counter++;
}
MessageBox.Show(messageText);
}
So I have the above code, it searches my CSV file for a match to every word in the messageText. The CSV file contains textspeak abbreviations and every time it finds a match it is to replace the word in messageText with the word it found. For example "hi LOL" would find "LOL, Laugh out loud" in the CSV and replace it
However this only works for one replacement. If I put in "Hi LOL" it would output "Hi LOL, Laugh out Loud"
But If I put "Hi LOL, how are you? LMAO" it outputs "Hi LOL LMFAO, Laughing my A** off, how are you?"
Can anyone tell me where I'm going wrong, I can't figure out why it is doing this
there are some issues with this method:
1 it takes 2 responsibilities (load key/value pair from csv file and replace text). everytime it's called, the csv file will be loaded.
2 the variable 'counter' looks weird for the purpose of the method.
here is the rewritten code:
static void Main(string[] args) {
var dictionary = LoadFromFile("c:\textWords.csv");
var message = "Hi LOL, LMAO";
message = ReplaceMessage(message, dictionary);
//
}
static Dictionary<String, String> LoadFromFile(String csvFile) {
var dictionary = new Dictionary<String, String>();
var lines = File.ReadAllLines(csvFile);
foreach (var line in lines) {
var fields = line.Split(',', '\r', '\n');
dictionary[fields[0].Trim()] = fields[1].Trim();
}
return dictionary;
}
static String ReplaceMessage(String message, Dictionary<String, String> dictionary) {
var words = message.Split(' ', ',');
var s = new StringBuilder();
foreach (var word in words) {
if (dictionary[word] != null) {
s.Append(String.Format("{0}, {1} ", word, dictionary[word]));
} else {
s.Append(word + " ");
}
}
return s.ToString().TrimEnd(' ');
}
This is whats going on. I have a huge text file that is suppose to be 1 line per entry. The issue is sometimes the line is broken with a new line.
I edit this entire file and wherever the file doesn't begin with ("\"A) i need to append the current line to the previous line ( replacing \n with " "). Everything I come up with keeps appending the line to a new line. Any help is appricated...
CODE:
public void step1a()
{
string begins = ("\"A");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
Example:
Orig:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no
pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
Resulting:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
my problem isnt the finding the if (line.StartsWith(begins)) its the else statement, it appends line2 to a new line
it seems like your string is not well formated...
try this "\"\\\"A\"" instead
public void step1a()
{
string begins = ("\"\\\"A\"");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
This does what you want:
CopyFileRemovingStrayNewlines(#"C:\ext.txt", #"C:\xt2.txt", #"""\""A");
With this method:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
File.AppendAllText(destinationPath, Environment.NewLine);
else
firstLine = false;
File.AppendAllText(destinationPath, line);
}
else
{
File.AppendAllText(destinationPath, " ");
File.AppendAllText(destinationPath, line);
}
}
}
It does have the problem of appending to an existing file, though. I suggest using a StreamWriter rather than AppendAllText. Like this:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
using (StreamWriter writer = new StreamWriter(destinationPath, false))
{
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
writer.WriteLine();
else
firstLine = false;
writer.Write(line);
}
else
{
writer.Write(" ");
writer.Write(line);
}
}
}
}
Your problem is that the \ is a C# escape code.
Your string is parsed as "A, because \" is the escape code for a single ".
You should make the begins string an #-string, which does not use escape codes.
You will then need to escape the " by doubling it up.
For example:
const string begins = #"\""A";
Note that the best way to do this is to use a StreamWriter, like this:
using(StreamWriter writer = File.Create(#"C:\xt2.txt"))
{
foreach (string line in lines)
{
if (line.StartsWith(begins))
writer.WriteLine(); //Close the previous line
writer.Write(line);
}
}
Based on #SLaks's example here is some code that should do the trick:
public static void step1a()
{
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
using (StreamWriter writer = new StreamWriter(File.Create(#"C:\xt2.txt")))
{
string buffer = null;
foreach (string line in lines)
{
if (!line.StartsWith(begins))
{
writer.WriteLine(buffer + line);
buffer = null;
}
else
{
if (buffer != null)
writer.WriteLine(buffer);
buffer = line;
}
}
if(buffer != null)
Console.Out.WriteLine(buffer);
}
}
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);
}
}