How to replace an actual "\n" string, not the line break escape - c#

I've been trying for the last two hours, but i can't replace the string \n, this is what i did:
Encoding enc = Encoding.ASCII;
for (int i = 0; i < numpntr; i++)
{
bw.BaseStream.Position = strt + i*var;
bw.Write(
enc.GetBytes(listView1.Items[i].SubItems[1].Text.Replace("\n","\x0A") + (new string('\0',
bytecnt - enc.GetByteCount(listView1.Items[i].SubItems[1].Text.Replace("\n" + "\x0A"))))));
}
bw.Flush();
bw.Close();
bw = null;
is there anyway to replace it as a string ?

You could use " \\n " or you can put ' # ' begining of your string like this:
enc.GetBytes(listView1.Items[i].SubItems[1].Text.Replace(#"\n" + "\x0A")
They are called verbatim strings, you can take a look at this documentation.

Related

When use String.Insert(int index, string text) insert at the end of the new string: "00000"

I need to insert in a specific position of the string line, another string, so I compute the specific position for start to insert:
string info1 = "info1";
string info2 = "info2";
string info3 = "info3";
string info4 = "info4";
string keyWord = "BELEGIT";
start = line.IndexOf(keyWord, 0) + keyWord.Length + 13;
var aStringBuilder = new StringBuilder(line);
aStringBuilder.Remove(start, 19);
line = aStringBuilder.ToString();
string newLine = line.Insert(start, "\r\n" + info1 + "\r\n" + "\r\n" + info2 + "\r\n" + info3 + "\r\n" + info4 + "\r\n");
(newLine will be the content of a file in my application).
newline contains the correct content except the string "00000" that inserts after "info4". So in my new file with the content that is newline there is newline and immediately after "00000". I do not really understand why.
Thanks in advance.
INPUT:
line contains:
#~11\r\nT-02040121R\r\n\r\n\r\n\r\n\r\n\r\n\n2.000000000\r\n
OUTPUT
newLine contains:
#~11\r\nT-02040121R\r\ninfo1\r\n\r\ninfo2\r\ninfo3\r\ninfo4\r\n00000\r\n
Assuming that you want just the first 19 chars of lineyou could use Substringto get them and string.Formatto build the new string.
Something like this
var start = line.Substring(0, 19);
string newLine = $"{start}\r\n{info1}\r\n\r\n{info2}\r\n{info3}\r\n{info4}\r\n";
The second line is the short form for
string newLine = string.Format("{0}\r\n{1}\r\n\r\n{2}\r\n{3}\r\n{4}\r\n", start, info1, info2, info3, info4);
if you need more information about string.Formathave a look at the MSDN.

C# Encode connection string from win1251 to utf8 and back

I'm trying to work around the problem with connection string encoding in Firebird .net provider ver >= 5.6.0.0 (current is 5.8.0.0). The full description of the problem (if you are interested in) is here, but I think I could explain it briefly. So let's start! I have a system default encoding win1251 and a connection string that contains a param calls "DbPath" with value
"F:\\Рабочая\\БД\\2.14.1\\January_2017\\MYDB.IB"
When I pass this connection string to firebird .net provider it takes "DbPath" param from connection string and get bytes from its value using Encoding.UTF-8. That's how it looks in their code:
protected virtual void SendAttachToBuffer(DatabaseParameterBuffer dpb, string database)
{
XdrStream.Write(IscCodes.op_attach);
XdrStream.Write(0);
if (!string.IsNullOrEmpty(Password))
{
dpb.Append(IscCodes.isc_dpb_password, Password);
}
//database is DbPath
XdrStream.WriteBuffer(Encoding.UTF8.GetBytes(database));
XdrStream.WriteBuffer(dpb.ToArray());
}
As you see they don't convert encoding from win1251 to utf-8, they just get bytes using Encoding.UTF8.GetBytes();
And later in their code I see that they just get a string using current Encoding (Encoding.Default):
public string GetString(byte[] buffer, int index, int count)
{
//_encoding is Encoding.Default == win1251
return _encoding.GetString(buffer, index, count);
}
And the result of this lines of code is that I get an I/O Exception cause my DbPath becomes to
"F:\\Рабочая\\БД\\2.14.1\\January_2017\\MYDB.IB"
So the first thing that I've tried is to convert my connection string to utf-8
using this lines of code:
private static string Win1251ToUTF8(string source)
{
Encoding utf8 = Encoding.GetEncoding("utf-8");
Encoding win1251 = Encoding.GetEncoding("windows-1251");
byte[] win1251Bytes = win1251.GetBytes(source);
byte[] utf8bytes = Encoding.Convert(win1251, utf8, win1251Bytes);
source = utf8.GetString(utf8bytes);
return source;
//Actually I'm not sure that I'm converting Encoding correctly
}
But it didn't affect. I've tried many variants with Encoding.Convert but I've not a solution yet. Can someone tell me please what I'm doing wrong and how I can solve the problem. Regards.
I recommend you to try the following code, maybe it helps you. Create a new C# WindowsFormApplication, put a BIG multiline texBox "textBox1" and a button "button1" on it. In the button click handler put this code:
// ----- The work -------------------------------------------------
string source = "F:\\\\Рабочая\\\\БД\\\\2.14.1\\\\January_2017\\\\MYDB.IB";
Encoding utf8 = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
Encoding win1251 = Encoding.GetEncoding("windows-1251");
byte[] utf8Bytes = utf8.GetBytes(source);
byte[] win1251Bytes = win1251.GetBytes(source);
byte[] utf8ofwinBytes = Encoding.Convert(win1251, utf8, win1251Bytes);
string unicodefromutf8 = utf8.GetString(utf8Bytes);
string unicodefromwin1251 = win1251.GetString(win1251Bytes);
// ----- The show -------------------------------------------------
textBox1.Text = "";
textBox1.Text += "Literal Unicode soource" + Environment.NewLine;
textBox1.Text += source + Environment.NewLine + Environment.NewLine;
string s1 = "";
textBox1.Text += "UTF8" + Environment.NewLine;
for (int i = 0; i < utf8Bytes.Length; i++)
{
s1 += utf8Bytes[i].ToString() + ", ";
}
textBox1.Text += s1 + Environment.NewLine + Environment.NewLine;
s1 = "";
textBox1.Text += "WIN 1251" + Environment.NewLine;
for (int i = 0; i < win1251Bytes.Length; i++)
{
s1 += win1251Bytes[i].ToString() + ", ";
}
textBox1.Text += s1 + Environment.NewLine + Environment.NewLine;
s1 = "";
textBox1.Text += "UTF8 of WIN 1251" + Environment.NewLine;
for (int i = 0; i < utf8ofwinBytes.Length; i++)
{
s1 += utf8ofwinBytes[i].ToString() + ", ";
}
textBox1.Text += s1 + Environment.NewLine + Environment.NewLine;
textBox1.Text += "Unicode string of UTF8 bytes" + Environment.NewLine;
textBox1.Text += unicodefromutf8 + Environment.NewLine + Environment.NewLine;
textBox1.Text += "Unicode string of WIN 1251 bytes" + Environment.NewLine;
textBox1.Text += unicodefromwin1251 + Environment.NewLine + Environment.NewLine;
Run it, click the button and you will see, all converting, encoding is done as it should.
You asked for a way to convert Unicode to UTF8 to WIN1251 to UTF8 to UNICODE - here it is.
Your misunderstanding may be:
source = utf8.GetString(utf8bytes);
return source;
This will convert the created UTF8 byte sequence array to an Unicode string. So you return an Unicode string, not a UTF8-byte-sequence of your win-1251 string. Exactly, you return the same string you get.
You have to push the (proper zero terminated) UTF8-byte-sequence to the .Net provider.
Use Encoding.Convert to convert charsets:
Encoding utf8 = Encoding.UTF8;
Encoding win = Encoding.GetEncoding("windows-1251");
byte[] winBytes = win.GetBytes(source);
byte[] utfBytes = Encoding.Convert(win, utf8, winBytes);
string result = utf8.GetString(utfBytes);

RichTextBox not printing newline

I have this method that replaces(in bold) some words in a string and show the changed string in a ritchtextBox.
In the final string I need to replace the # symbol by a newline.
I already tried checked this forum tying several solutions, but nothing worked.
The method I use is
private string bold(string ing)
{
StringBuilder builder = new StringBuilder();
ing = " " + ing + " ";
builder.Append(#"{\rtf1\ansi");
foreach (string word in splitwords)
{
var regex = new Regex(#"(?<![\w])" + word + #"(?![\w])", RegexOptions.IgnoreCase);
ing = regex.Replace(ing, m => #"\b" + m.ToString() + #"\c0");
}
ing = ing.Replace(#"\b", #"\b ");
ing = ing.Replace(#"\c0", #" \b0");
ing = ing.Replace("#", Environment.NewLine);
builder.Append(ing);
builder.Append(#"}");
MessageBox.Show("builder.ToString():" + builder.ToString());
return builder.ToString();
}
When I call the this method and "put it" in the ritchTextBox it doesn´t print the new line
ingred.Rtf = bold(ingd);
How should I solve this??
EDIT:: input string - line1 # line2 # line3
output in the MessageBox
Builder.ToString() : {\rtf1\ansi\b line1\b0
line2
line3
}
output in the ritchTextBox: line1 line2 line3
Instead of
ing = ing.Replace("#", Environment.NewLine);
Try
ing = ing.Replace("#", #"\par\r\n");
Use This Code For Repalce
int startIndex = 0, index;
RichTextBox myRtb = new RichTextBox(); // if have A richtextBox Remove thisline and Use your Richtextbox
myRtb.Rtf = STRRTF;// if have A richtextBox Remove thisline and Use your Richtextbox
while ((index = myRtb.Text.IndexOf("#", startIndex)) != -1)
{
myRtb.Select(index, word.Length);
myRtb.SelectedText ="\n";
startIndex = index + 1;
}
Better use Environment.NewLine for adding new line also Make sure yourRTB.MultiLine property is set to true. assign string to richtext box like this yourRTB.AppendText(t)
Try replacing it with a "\r\n" character sequence?
edit: is MultiLine property of ritchtextBox enabled?

Regex catch string between strings

I created a small function to catch a string between strings.
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
However if i call my function like this: _StringBetween("[18][20][3][5][500][60]", "[", "]");
It will fail. A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
However i can not because i dont know if the character is going to be a bracket or a word.
Sorry if this is a stupid question but i couldn't find something similar searching.
A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; However i can not because i don't know if the character is going to be a bracket or a word.
You can escape all meta-characters by calling Regex.Escape:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
This would cause the content of sStart and sEnd to be interpreted literally.

String: replace last ".something" in a string?

I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}

Categories

Resources