I'm not new to C# and I work with strings all the time but I just can't understand why in this case I can't add a simple character to a simple string!
I'm trying to read a text file into C# so that I can later insert it into a SQL server table.
Anyway, I'm stuck on adding a single quote character to a string. My code is as follows:
string text;
using (var streamReader = new StreamReader(#"The_Directory\myTextFile.txt", Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
string[] lines = text.Split(new Char[] { '\n' });
string rearrange;
foreach (string line in lines)
{
rearrange = "*" + line + "'";
Console.WriteLine(rearrange);
}
What I get as a result doesn't contain the character that I wish to add to the end of the string and only contains the character that I wanted to add to the end, at the beginning.
The output is like this:
'The first line
'The second line
I can't understand why it doesn't perform the simple string addition. I tried to filter out any possible additional \n character in the lines but it didn't help.
As pointed out by #Olivier, you are splitting on \n rather than \r\n. That may mean there is still a \r character (carriage return) at the end of every line you read. The resulting output is then:
*The first line\r'
*The second line\r'
which, on a typical terminal emulator, is displayed as:
'The first line
'The second line
If you could slow down the terminal output, you'd see the * is initially there at the start of the line, before being overwritten by the '.
One way to get rid of the clutter is to strip off trailing whitespace:
rearrange = "*" + line.TrimEnd() + "'";
Note: None of this will work for files produced on a 'classic' Mac, where newline is a carriage return without linefeed.
I'd recommend following Olivier's answer.
Just try this:
using System.IO;
string[] lines = File.ReadAllLines("The_Directory\myTextFile.txt", Encoding.UTF8);
string rearrange;
foreach (string line in lines)
{
rearrange = "*" + line + "'";
Console.WriteLine(rearrange);
}
On Windows, new line is Environment.Newline = "\r\n".
Splitting only on '\n' causes that the remaining '\r' implies a go to the start of the current line and the * is replaced by a ' when outputed to the console, hence the result.
Because the \n historically in DOS causes the cursor only to go to down in the column, if I remember correctly, but I'm not sure, so the need of the \r too.
https://fr.wikipedia.org/wiki/Carriage_Return_Line_Feed
Just try the following small modification in the "Split":
string text;
using (var streamReader = new StreamReader(#"The_Directory\myTextFile.txt",Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
string[] lines = text.Replace("\r\n","\n").Split("\n");
string rearrange;
foreach (string line in lines)
{
rearrange = "*" + line + "'";
Console.WriteLine(rearrange);
}
Usually, a normal (Windows) UTF-8 text file has both \r\n on the end of each line. If you split just by \n, then the remaining \r will remain and the result of displaying the \r on the console is that the cursor jumps to the beginning of the current line, before displaying the next character. Thus, it would overwrite the line with the following characters while displaying further text.
2 Things. Try string.split with stringsplitoptions.RemoveEmptyEntries.
And for the StringBuilding use a StringBuilder instead of concatenating it.
string local= HttpUtility.HtmlDecode(GetLocalizedSupportPhone()).Replace("-", "").Replace(" ", "");
I am getting a string :
"0124 4148173"
from the GetLocalizedSupportPhone() method. The Html Decode method returns:
"0-12-4 41-481-73"
I have a list of phone numbers like:- "01244148173", "01244148173", etc which are plain integers without any space character or html character.
Problem scenario:- All i want to do is to get decoded local string ("0-12-4 41-481-73"), replace the as well as " " with empty string character and compare the resultant local string with the list items. If a similar list item exists, then remove that particular list item.
But strangely, the .Replace() method replaces space character with blank string but is unable to replace "-" with empty string.
I am just curious why is it happening? Why ANY OF THE STRING METHODS (like I tried with .split() ) can not detect "-"?
There are different types of hyphens. is a soft hyphen. Specifically the soft hyphen is 173 and the hyphen on your keyboard is 45.
Try this instead.
var r = HttpUtility.HtmlDecode("0124 4148173")
.Replace((char)173, ' ')
.Replace(" ", "");
That will replace the soft hyphen with a space and then your second replace will get rid of that.
Another option would be to use a regular expression to remove all non-numeric values.
Regex nonNumeric = new Regex(#"\D");
var r = nonNumeric.Replace(
HttpUtility.HtmlDecode("0124 4148173"),
string.Empty);
This might help if you're just looking to strip spaces and soft hypens from a string without having to deal with HTML decoding:
var regex = new Regex(#"\u00ad| ");
var result = regex.Replace(stringWithSoftHyphens, string.Empty);
I tried doing this with Trim((char)173) but it (and methods like Split) do not seem to be able to handle the soft hyphen character like the Regex class can.
I wanted to know if there is a solution to the problem mentioned in the topic.
Example:
In my project I have to parse a lot of messages. These messages contain formatting characters like "\n" or "\r".
The end of this message is always signed with the name of the author.
Now I want to remove the signatures from each message. The problem is that the end of the message could look like
\r\n\rDaniel Walters\n\r\n
\n\r\n\r\n\rDaniel
or something else
The problem is that I don't know how to identifiy these varying endings.
I tried to only remove the last "\n\r\n"'s by calling string.EndsWith() in a loop but this solution only removes everything except "\r\n\rDaniel Walter".
Then I tried to remove the author (I parsed it prior to this step) but this does not work either. Sometimes the parsed author is "Daniel Walters" and the signature is only "Daniel".
Any ideas how to solve this?
Are there maybe some easier and smarter solutions than looping through the string?
You can make a regular expression to replace the name with an optional last name, and any number of whitespace characters before and after.
Example:
string message = "So long and thanks for all the fish \t\t\r Arthur \t Dent \r\r\n ";
string firstName = "Arthur";
string lastName = "Dent";
string pattern = "\\s+" + Regex.Escape(firstName) + "(\\s+" + Regex.Escape(lastName) + ")?\\s*$";
message = Regex.Replace(message, pattern, String.Empty);
(Yes, I know it was really the dolphins saying that.)
you could try something like the following (untested) :-
string str="\r\n\rDaniel Walters\n\r\n";
while(str.EndsWith("\r") || str.EndsWith("\n"))
{
// \r and \n have the same length. So, we can use either \r or \n in the end
str=str.SubString(0,str.Length - ("\r".Length));
}
while(str.StartsWith("\r") || str.StartsWith("\n"))
{
// \r and \n have the same length
str=str.SubString("\r".Length,str.length);
}
You'll have to determine what "looks like" a signature. Are there specific criteria that always apply?
Always followed by at least 3 newlines (\r or \n)
Starts with a capital letter
Has no following text
A regex like this might work for those criteria:
/[\r\n]{3,}[A-Z][\w ]+[\r\n]*(?!\w)/
Adjust according to your needs.
Edited to add: This should match the last "paragraph" of a document.
/([\r\n]+[\w ]+[\r\n]*)(?!.)/
you can do this as well but I am not sure if your pattern changes but this will return Daniel Walter
string replaceStr = "\r\n\rDaniel Walters\n\r\n";
replaceStr = replaceStr.TrimStart(new char[] { '\r', '\n' });
replaceStr = replaceStr.TrimEnd(new char[] { '\r', '\n' });
or if you want to use the trim method you can do the following
string replaceStr = "\r\n\rDaniel Walters\n\r\n";
replaceStr = replaceStr.Trim();
A different approach could be to split your message at the newline chars removing the empty newline entries. Then reassembling the expected string excluding the last line where I assume there is always the signature.
string removeLastLine = "Text on the firstline\r\ntest on second line\rtexton third line\r\n\rDaniel Walters\n\r\n";
string[] lines = removeLastLine.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
lines = lines.Take(lines.Length - 1).ToArray();
string result = string.Join(Environment.NewLine, lines);
I have the following input:
string txt = " i am a string "
I want to remove space from start of starting and end from a string.
The result should be: "i am a string"
How can I do this in c#?
String.Trim
Removes all leading and trailing white-space characters from the current String object.
Usage:
txt = txt.Trim();
If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:
char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);
Source
You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.
NOTE
As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.
It would be better to call the default .Trim() and then call the method with your list of characters.
You can use:
String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
String.Trim - combination of the two functions above
Usage:
string txt = " i am a string ";
char[] charsToTrim = { ' ' };
txt = txt.Trim(charsToTrim)); // txt = "i am a string"
EDIT:
txt = txt.Replace(" ", ""); // txt = "iamastring"
I really don't understand some of the hoops the other answers are jumping through.
var myString = " this is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";
It's not rocket science.
txt = txt.Trim();
Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.
text.Trim() is to be used
string txt = " i am a string ";
txt = txt.Trim();
Use the Trim method.
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(#"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, #" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, #" ");
Console.WriteLine(s4);
Console.ReadLine();
}
OUTPUT:
He saw a cute dog.
There was another sentence.
He saw a cute dog.
You Can Use
string txt = " i am a string ";
txt = txt.TrimStart().TrimEnd();
Output is "i am a string"
How can I replace Line Breaks within a string in C#?
Use replace with Environment.NewLine
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.
The solutions posted so far either only replace Environment.NewLine or they fail if the replacement string contains line breaks because they call string.Replace multiple times.
Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.
string result = Regex.Replace(input, #"\r\n?|\n", replacementString);
To extend The.Anyi.9's answer, you should also be aware of the different types of line break in general use. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
should get you going...
I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.
Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.
line = line.Replace(Environment.NewLine, "newLineReplacement");
However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.
if you want to "clean" the new lines, flamebaud comment using regex #"[\r\n]+" is the best choice.
using System;
using System.Text.RegularExpressions;
class MainClass {
public static void Main (string[] args) {
string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";
Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
/* Result:
AAA
-BBB
-
-
-CCC
DDD---EEE
*/
Console.WriteLine (Regex.Replace(str, #"\r\n?|\n", "-"));
// Result:
// AAA-BBB---CCC---DDD---EEE
Console.WriteLine (Regex.Replace(str, #"[\r\n]+", "-"));
// Result:
// AAA-BBB-CCC-DDD-EEE
}
}
Use new in .NET 6 method
myString = myString.ReplaceLineEndings();
Replaces ALL newline sequences in the current string.
Documentation:
ReplaceLineEndings
Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use #Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.
string line = ...
line = line.Replace( "\r", "").Replace( "\n", "" );
As extension methods:
public static class StringExtensions
{
public static string RemoveLineBreaks( this string lines )
{
return lines.Replace( "\r", "").Replace( "\n", "" );
}
public static string ReplaceLineBreaks( this string lines, string replacement )
{
return lines.Replace( "\r\n", replacement )
.Replace( "\r", replacement )
.Replace( "\n", replacement );
}
}
To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
and in this order, to not to make extra line breaks, when you find some combination of line ending chars.
Why not both?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), #"(\r\n?|\n)", ReplacementString);
Note: Replace strin with the name of your input string.
I needed to replace the \r\n with an actual carriage return and line feed and replace \t with an actual tab. So I came up with the following:
public string Transform(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}
var answer = Regex.Replace(value, "(\n|\r)+", replacementString);
As new line can be delimited by \n, \r and \r\n, first we’ll replace \r and \r\n with \n, and only then split data string.
The following lines should go to the parseCSV method:
function parseCSV(data) {
//alert(data);
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
}
Use the .Replace() method
Line.Replace("\n", "whatever you want to replace with");
Best way to replace linebreaks safely is
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
that should produce a string with only \n (eg linefeed) as linebreaks.
this code is usefull to fix mixed linebreaks too.
Another option is to create a StringReader over the string in question. On the reader, do .ReadLine() in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a StringBuilder and call .AppendLine on it.
The advantage is, you let the framework decide what constitutes a "line break".
string s = Regex.Replace(source_string, "\n", "\r\n");
or
string s = Regex.Replace(source_string, "\r\n", "\n");
depending on which way you want to go.
Hopes it helps.
If you want to replace only the newlines:
var input = #"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = #"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(#"\n", replaceWith).Replace(#"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);
If you want to replace newlines, tabs and white spaces:
var input = #"sdfhlusdkuidfs\r\ndfgdgfd";
var match = #"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);
This is a very long winded one-liner solution but it is the only one that I had found to work if you cannot use the the special character escapes like "\r" and "\n" and \x0d and \u000D as well as System.Environment.NewLine as parameters to thereplace() method
MyStr.replace( System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString );
This is somewhat offtopic but to get it to work inside Visual Studio's XML .props files, which invoke .NET via the XML properties, I had to dress it up like it is shown below.
The Visual Studio XML --> .NET environment just would not accept the special character escapes like "\r" and "\n" and \x0d and \u000D as well as System.Environment.NewLine as parameters to thereplace() method.
$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))
Based on #mark-bayers answer and for cleaner output:
string result = Regex.Replace(ex.Message, #"(\r\n?|\r?\n)+", "replacement text");
It removes \r\n , \n and \r while perefer longer one and simplify multiple occurances to one.