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);
}
}
Related
using System;
using System.IO;
namespace GetFilesFromDirectory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write your Name of Disc");
string myDisc = Console.ReadLine();
string myDisc1 = "#\"";
Console.WriteLine("Write your Directory");
string myDir1 = Console.ReadLine();
string myDir = ":\\";
string myDir2 = "\\\"";
string myPath = myDisc1 + myDisc + myDir + myDir1 + myDir2;
Console.WriteLine(myPath);
string[] filePaths = Directory.GetFiles(myPath);
foreach (var files in filePaths)
{
Console.WriteLine(files);
}
Console.ReadLine();
}
}
}
Try this
static void Main(string[] args)
{
Console.WriteLine("Write your Name of Disc");
//You need to add :\ to make it a fullPath
string myDisc = Console.ReadLine()+":\\";
Console.WriteLine("Write your Directory");
string myDir1 = Console.ReadLine();
string myPath = Path.Combine(myDisc , myDir1);
Console.WriteLine(myPath);
string[] filePaths = Directory.GetFiles(myPath);
foreach (var files in filePaths)
{
Console.WriteLine(files);
}
Console.ReadLine();
}
What are you doing is creating a string wich is the literal reprentation of the string you want but you don't need to do this.For example if you write this:
string path=#"c:\dir\subdir"; its real value will be c:\dir\subdir
instead this "#\"c:\\dir\\subdir\""; will be
#"c:\dir\subdir"
Read these articles to better understand string literals and verbatim strings https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx https://msdn.microsoft.com/en-us/library/362314fe.aspx
https://msdn.microsoft.com/en-us/library/h21280bw.aspx
From what I can tell your myPath will look like #"discName:\dirName\", you don't need to append the #" or ".
These symbols are used when you are creating a new string variable to note that is a String literal, but you are including these characters in the actual string you are generating.
In other words, remove myDisc1 and myDir2
Better than that, as noted by DrKoch
string myPath = Path.Combine(myDisc + #":\", myDir1);
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;
}
}
How to remove whitespaces between characters in c#?
Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".
But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?
You could use String.Replace method
string str = "C Sharp";
str = str.Replace(" ", "");
or if you want to remove all whitespace characters (space, tabs, line breaks...)
string str = "C Sharp";
str = Regex.Replace(str, #"\s", "");
If you want to keep one space between every word. You can do it this way as well:
string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Use String.Replace to replace all white space with nothing.
eg
string newString = myString.Replace(" ", "");
if you want to remove all spaces in one word:
input.Trim().Replace(" ","")
And If you want to remove extra spaces in the sentence, you should use below:
input.Trim().Replace(" +","")
the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.
If you want to keep one space between every word. this should do it..
public static string TrimSpacesBetweenString(string s)
{
var mystring =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
string result = string.Empty;
foreach (var mstr in mystring)
{
var ss = mstr.Trim();
if (!string.IsNullOrEmpty(ss))
{
result = result + ss+" ";
}
}
return result.Trim();
}
it will remove the string in between the string
so if the input is
var s ="c sharp";
result will be "c sharp";
//Remove spaces from a string just using substring method and a for loop
static void Main(string[] args)
{
string businessName;
string newBusinessName = "";
int i;
Write("Enter a business name >>> ");
businessName = ReadLine();
for(i = 0; i < businessName.Length; i++)
{
if (businessName.Substring(i, 1) != " ")
{
newBusinessName += businessName.Substring(i, 1);
}
}
WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
var str=" c sharp "; str = str.Trim();
str = Regex.Replace(str, #"\s+", " "); ///"c sharp"
string myString = "C Sharp".Replace(" ", "");
I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:
namespace XXX.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage
{
get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
}
}
}
So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.
What would an implementation of 'MagicFunction' look like to make the following (nunit) test pass?
public MagicFunction_Should_Prepend_Given_String_To_Each_Line()
{
var str = #"line1
line2
line3";
var result = MagicFunction(str, "-- ");
var expected = #"-- line1
-- line2
-- line3";
Assert.AreEqual(expected, result);
}
string MagicFunction(string str, string prepend)
{
str = str.Replace("\n", "\n" + prepend);
str = prepend + str;
return str;
}
EDIT:
As others have pointed out, the newline characters vary between environments. If you're only planning to use this function on files that were created in the same environment then System.Environment will work fine. However, if you create a file on a Linux box and then transfer it over to a Windows box you'll want to specify a different type of newline. Since Linux uses \n and Windows uses \r\n this piece of code will work for both Windows and Linux files. If you're throwing Macs into the mix (\r) you'll have to come up with something a little more involved.
Use .Select on a list of the lines.
private static string MagicFunction(string str, string prefix)
{
string[] lines = str.Split(new[] { '\n' });
return string.Join("\n", lines.Select(s => prefix + s).ToArray());
}
How about:
string MagicFunction(string InputText) {
public static Regex regex = new Regex(
"(^|\\r\\n)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
// This is the replacement string
public static string regexReplace =
"$1-- ";
// Replace the matched text in the InputText using the replacement pattern
string result = regex.Replace(InputText,regexReplace);
return result;
}
var result = "-- " + str.Replace(Environment.NewLine, Environment.NewLine + "-- ");
if you want it cope with either Windows (\r\n) NewLines or Unix ones (\n) then:
var result = "-- " + str.Replace("\n", "\n-- ");
No need to touch the \r as it is to be left where it was before. If however you want to cross between Unix and Windows then:
var result = "-- " + str.Replace("\r","").Replace("\n", Enviornment.NewLine + "-- ");
Will do it and return the result in the local OS's format
You could do it like that :
public string MagicFunction2(string str, string prefix)
{
bool first = true;
using(StringWriter writer = new StringWriter())
using(StringReader reader = new StringReader(str))
{
string line;
while((line = reader.ReadLine()) != null)
{
if (!first)
writer.WriteLine();
writer.Write(prefix + line);
first = false;
}
return writer.ToString();
}
}
You could split the string by Environment.NewLine, and then add the prefix to each of those string, and then join them by Environment.NewLine.
string MagicFunction(string prefix, string orignalString)
{
List<string> prefixed = new List<string>();
foreach (string s in orignalString.Split(new[]{Environment.NewLine}, StringSplitOptions.None))
{
prefixed.Add(prefix + s);
}
return String.Join(Environment.NewLine, prefixed.ToArray());
}
How about this. It uses StringBuilder in case you are planning on prepending a lot of lines.
string MagicFunction(string input)
{
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(input);
string line = null;
using(StringReader sr = new StringReader(input))
{
while((line = sr.ReadLine()) != null)
{
sb.Append(String.Concat("-- ", line, System.Environment.NewLine));
}
}
return sb.ToString();
}
Thanks all for your answers. I implemented the MagicFunction as an extension method. It leverages Thomas Levesque's answer but is enhanced to handle all major environments AND assumes you want the output string to use the same newline terminator of the input string.
I favored Thomas Levesque's answer (over Spencer Ruport's, Fredrik Mork's, Lazarus, and JDunkerley) because it was the best performing. I'll post performance results on my blog and link here later for those interested.
(Obviously, the function name of 'MagicFunctionIO' should be changed. I went with 'PrependEachLineWith')
public static string MagicFunctionIO(this string self, string prefix)
{
string terminator = self.GetLineTerminator();
using (StringWriter writer = new StringWriter())
{
using (StringReader reader = new StringReader(self))
{
bool first = true;
string line;
while ((line = reader.ReadLine()) != null)
{
if (!first)
writer.Write(terminator);
writer.Write(prefix + line);
first = false;
}
return writer.ToString();
}
}
}
public static string GetLineTerminator(this string self)
{
if (self.Contains("\r\n")) // windows
return "\r\n";
else if (self.Contains("\n")) // unix
return "\n";
else if (self.Contains("\r")) // mac
return "\r";
else // default, unknown env or no line terminators
return Environment.NewLine;
}
Hey guys, thanks for all the help that you can provide. I need a little bit of regex help thats far beyond my knowledge.
I have a listbox with a file name in it, example 3123~101, a delimited file that has 1 line of text in it. I need to Regex everything after the last "\" before the last "-" in the text file. The ending will could contain a prefix then ###{####-004587}.txt The ~ formula is {### + ~# -1.
File name:
3123~101
So Example 1:
3123|X:directory\Path\Directory|Pre0{0442-0500}.txt
Result:
X:\directory\Path\Directory\Pre00542.txt
File name:
3123~101
So Example 1:
3123|X:directory\Path\Directory|0{0442-0500}.txt
Result:
X:\directory\Path\Directory\00542.txt
According your example I've created the following regexp:
\|(.)(.*)\|(.*)\{\d{2}(\d{2})\-(\d{2}).*(\..*)
The result should be as following:
group1 + "\\" + group2 + "\\" + group3 + group5 + group4 + group6
If you ain't satisfied, you can always give it a spin yourself here.
EDIT:
After remembering me about named groups:
\|(?<drive>.)(?<path>.*)\|(?<prefix>.*)\{\d{2}(?<number2>\d{2})\-(?<number1>\d{2}).*(?<extension>\..*)
drive + "\\" + path + "\\" + prefix + number1 + number2 + extension
public static string AdjustPath(string filename, string line)
{
int tilde = GetTilde(filename);
string[] fields = Regex.Split(line, #"\|");
var addbackslash = new MatchEvaluator(
m => m.Groups[1].Value + "\\" + m.Groups[2].Value);
string dir = Regex.Replace(fields[1], #"^([A-Z]:)([^\\])", addbackslash);
var addtilde = new MatchEvaluator(
m => (tilde + Int32.Parse(m.Groups[1].Value) - 1).
ToString().
PadLeft(m.Groups[1].Value.Length, '0'));
return Path.Combine(dir, Regex.Replace(fields[2], #"\{(\d+)-.+}", addtilde));
}
private static int GetTilde(string filename)
{
Match m = Regex.Match(filename, #"^.+~(\d+)$");
if (!m.Success)
throw new ArgumentException("Invalid filename", "filename");
return Int32.Parse(m.Groups[1].Value);
}
Call AdjustPath as in the following:
public static void Main(string[] args)
{
Console.WriteLine(AdjustPath("3123~101", #"3123|X:directory\Path\Directory|Pre0{0442-0500}.txt"));
Console.WriteLine(AdjustPath("3123~101", #"3123|X:directory\Path\Directory|0{0442-0500}.txt"));
}
Output:
X:\directory\Path\Directory\Pre00542.txt
X:\directory\Path\Directory\00542.txt
If instead you want to write the output to a file, use
public static void WriteAdjustedPaths(string inpath, string outpath)
{
using (var w = new StreamWriter(outpath))
{
var r = new StreamReader(inpath);
string line;
while ((line = r.ReadLine()) != null)
w.WriteLine("{0}", AdjustPath(inpath, line));
}
}
You might call it with
WriteAdjustedPaths("3123~101", "output.txt");
If you want a List<String> instead
public static List<String> AdjustedPaths(string inpath)
{
var paths = new List<String>();
var r = new StreamReader(inpath);
string line;
while ((line = r.ReadLine()) != null)
paths.Add(AdjustPath(inpath, line));
return paths;
}
To avoid repeated logic, we should define WriteAdjustedPaths in terms of the new function:
public static void WriteAdjustedPaths(string inpath, string outpath)
{
using (var w = new StreamWriter(outpath))
{
foreach (var p in AdjustedPaths(inpath))
w.WriteLine("{0}", p);
}
}
The syntax could be streamlined with Linq. See C# File Handling.
A slight variation on gbacon's answer that will also work in older versions of .Net:
static void Main(string[] args)
{
Console.WriteLine(Adjust("3123~101", #"3123|X:directory\Path\Directory|Pre0{0442-0500}.txt"));
Console.WriteLine(Adjust("3123~101", #"3123|X:directory\Path\Directory|0{0442-0500}.txt"));
}
private static string Adjust(string name, string file)
{
Regex nameParse = new Regex(#"\d*~(?<value>\d*)");
Regex fileParse = new Regex(#"\d*\|(?<drive>[A-Za-z]):(?<path>[^\|]*)\|(?<prefix>[^{]*){(?<code>\d*)");
Match nameMatch = nameParse.Match(name);
Match fileMatch = fileParse.Match(file);
int value = Convert.ToInt32(nameMatch.Groups["value"].Value);
int code = Convert.ToInt32(fileMatch.Groups["code"].Value);
code = code + value - 1;
string drive = fileMatch.Groups["drive"].Value;
string path = fileMatch.Groups["path"].Value;
string prefix = fileMatch.Groups["prefix"].Value;
string result = string.Format(#"{0}:\{1}\{2}{3:0000}.txt",
drive,
path,
prefix,
code);
return result;
}
You don't seem to be very clear in your examples.
That said,
/.*\\(.*)-[^-]*$/
will capture all text between the last backslash and the last hyphen in whatever it's matched against.