reversing text from input file using linq - c#

I would like to reverse each word from input.txt using c# and linq and display the output text, so far i have a code that inputs the word and reverses it.
using System;
using System.Text;
using System.Linq;
namespace program
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("String:");
string name = Console.ReadLine();
string output = new string(name.ToCharArray().Reverse().ToArray());
Console.WriteLine(output);
}
}
}

string input = "I love programming";
string output = String.Join(" ",
input.Split().Select(w => new String(w.Reverse().ToArray())));
// I evol gnimmargorp
Reading file is simple:
string input = File.ReadAllText("input.txt");
You can also move word reversing into separate method. That will allow you to change algorithm of string reversing without touching other logic:
private static string GetReversedString(string s)
{
return new String(s.Reverse().ToArray());
}
And getting reversed output will look like:
string output = String.Join(" ", input.Split().Select(GetReversedString));
If lines should be preserved:
string output =
String.Join(Environment.NewLine,
File.ReadLines().Select(l =>
String.Join(" ", l.Split().Select(GetReversedString))));

The reversal code could be refactored in an extension method for String; Next, a text file should be opened, the lines splitted to single words and the words mapped reversely to the console.

Related

C# Split a string and build a stringarray out of the string [duplicate]

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?
To split on a string you need to use the overload that takes an array of strings:
string[] lines = theText.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None
);
Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:
string[] lines = theText.Split(
new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);
What about using a StringReader?
using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
string line = reader.ReadLine();
}
Try to avoid using string.Split for a general solution, because you'll use more memory everywhere you use the function -- the original string, and the split copy, both in memory. Trust me that this can be one hell of a problem when you start to scale -- run a 32-bit batch-processing app processing 100MB documents, and you'll crap out at eight concurrent threads. Not that I've been there before...
Instead, use an iterator like this;
public static IEnumerable<string> SplitToLines(this string input)
{
if (input == null)
{
yield break;
}
using (System.IO.StringReader reader = new System.IO.StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
This will allow you to do a more memory efficient loop around your data;
foreach(var line in document.SplitToLines())
{
// one line at a time...
}
Of course, if you want it all in memory, you can do this;
var allTheLines = document.SplitToLines().ToArray();
You should be able to split your string pretty easily, like so:
aString.Split(Environment.NewLine.ToCharArray());
Based on Guffa's answer, in an extension class, use:
public static string[] Lines(this string source) {
return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}
Regex is also an option:
private string[] SplitStringByLineFeed(string inpString)
{
string[] locResult = Regex.Split(inpString, "[\r\n]+");
return locResult;
}
For a string variable s:
s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
This uses your environment's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#'s escape characters \r\n.
This is a reliable solution, because if you recombine the lines with String.Join, this equals your original string:
var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);
What not to do:
Use StringSplitOptions.RemoveEmptyEntries, because this will break markup such as Markdown where empty lines have syntactic purpose.
Split on separator new char[]{Environment.NewLine}, because on Windows this will create one empty string element for each new line.
I just thought I would add my two-bits, because the other solutions on this question do not fall into the reusable code classification and are not convenient.
The following block of code extends the string object so that it is available as a natural method when working with strings.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.ObjectModel;
namespace System
{
public static class StringExtensions
{
public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
{
return s.Split(new string[] { delimiter }, options);
}
}
}
You can now use the .Split() function from any string as follows:
string[] result;
// Pass a string, and the delimiter
result = string.Split("My simple string", " ");
// Split an existing string by delimiter only
string foo = "my - string - i - want - split";
result = foo.Split("-");
// You can even pass the split options parameter. When omitted it is
// set to StringSplitOptions.None
result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
To split on a newline character, simply pass "\n" or "\r\n" as the delimiter parameter.
Comment: It would be nice if Microsoft implemented this overload.
Starting with .NET 6 we can use the new String.ReplaceLineEndings() method to canonicalize cross-platform line endings, so these days I find this to be the simplest way:
var lines = input
.ReplaceLineEndings()
.Split(Environment.NewLine, StringSplitOptions.None);
I'm currently using this function (based on other answers) in VB.NET:
Private Shared Function SplitLines(text As String) As String()
Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
End Function
It tries to split on the platform-local newline first, and then falls back to each possible newline.
I've only needed this inside one class so far. If that changes, I will probably make this Public and move it to a utility class, and maybe even make it an extension method.
Here's how to join the lines back up, for good measure:
Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
Return String.Join(Environment.NewLine, lines)
End Function
Well, actually split should do:
//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);
//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
Console.WriteLine("{0}: {1}", i, splitted[i]);
}
string[] lines = text.Split(
Environment.NewLine.ToCharArray(),
StringSplitOptions.RemoveEmptyStrings);
The RemoveEmptyStrings option will make sure you don't have empty entries due to \n following a \r
(Edit to reflect comments:) Note that it will also discard genuine empty lines in the text. This is usually what I want but it might not be your requirement.
I did not know about Environment.Newline, but I guess this is a very good solution.
My try would have been:
string str = "Test Me\r\nTest Me\nTest Me";
var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();
The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.
EDIT:
As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.
Examples here are great and helped me with a current "challenge" to split RSA-keys to be presented in a more readable way. Based on Steve Coopers solution:
string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
{
//Spit each string into a n-line length list of strings
var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
//Check if there are any characters left after split, if so add the rest
if(txt.Length > ((txt.Length / n)*n) )
Lines.Add(txt.Substring((txt.Length/n)*n));
//Create return text, with extras
string txtReturn = "";
foreach (string Line in Lines)
txtReturn += AddBefore + Line + AddAfterExtra + Environment.NewLine;
return txtReturn;
}
Presenting a RSA-key with 33 chars width and quotes are then simply
Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));
Output:
Hopefully someone find it usefull...
Silly answer: write to a temporary file so you can use the venerable
File.ReadLines
var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
writer.Write(s);
}
var lines = File.ReadLines(path);
using System.IO;
string textToSplit;
if (textToSplit != null)
{
List<string> lines = new List<string>();
using (StringReader reader = new StringReader(textToSplit))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
lines.Add(line);
}
}
}
Very easy, actually.
VB.NET:
Private Function SplitOnNewLine(input as String) As String
Return input.Split(Environment.NewLine)
End Function
C#:
string splitOnNewLine(string input)
{
return input.split(environment.newline);
}

How to delete the first 2 lines from string in C#?

I have a string like the following:
string myString = #"This is the first line
This is the third line as the 2nd is empty
The string continues
Anso so on ...
...
..
.";
I know that I can split this into an array, delete the first 2 elements and then rebuild my string from that array but I'm looking for something much more simple.
myString = String.Join("\n", myString.Split('\n').Skip(2));
Here's #maccettura's fiddle of that code with your string literal.
To break that down:
Split on newlines, return a sequence of segments -- the segments are lines, since we split on newline:
myString.Split('\n')
Skip the first two segments, return the rest of the a sequence
.Skip(2)
And rejoin the shorter sequence with newlines:
String.Join("\n", ...
This is just what you were contemplating doing in a loop, but with Skip(), it can be expressed as a readable one-liner.
Lastly, here's #user1242967 's version of the Split() call, which will handle \r\n newlines:
myString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
If you do want to micro-optimize (or your strings are large, or you're calling this in a loop), here is a more performant way to do it:
private static string RemoveFirstTwoLines(string myString) {
int ix = myString.IndexOf('\n');
ix = myString.IndexOf('\n', ix + 1);
return myString.Substring(ix + 1);
}
Good for large strings, code easy to read:
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main (string[] args)
{
var text = "line 1\r\nline 2\r\nline 3\r\nline 4";
using (var sr = new StringReader (text))
{
sr.ReadLine ();
sr.ReadLine ();
string result = sr.ReadToEnd ();
}
}
}
}

how can i trim the string in c# after each file extension name

I have a string of attachments like this:
"SharePoint_Health Check Assessment.docx<br>Tes‌​t Workflow.docx<br>" .
and i used this method :
AttachmentName = System.Text.RegularExpressions.Regex.Replace(AttachmentName, #"<(.|\n)*?>", "String.Empty");
and i got result :
SharePoint_Health Check Assessment.docxTest Workflow.docx
How can i split the string using c# and get the result with each file name seperately like :
SharePoint_Health Check Assessment.docx
Test Workflow.docx
and then show them into some control one by one.
and after that i want just the URL of the string like
"http://srumos1/departments/Attachments/2053_3172016093545_ITPCTemplate.txt"
and
"http://srumos1/departments/Attachments/2053_3172016093545_ITPCTemplate.txt"
how can i do that
i got it this way
AttachmentName = Regex.Replace(AttachmentName, #"<(.|\n)*?>", string.Empty);
Well there's your problem. You had valid delimiter but stripped them away for some reason. Leave the delimiters there and use String.Split to split them based on that delimiter.
Or replace the HTML with a delimiter instead of an empty string:
AttachmentName = Regex.Replace(AttachmentName, #"<(.|\n)*?>", "|");
And then split based off of that:
string[] filenames = AttachmentName.Split(new [] {'|'},
StringSplitOptions.RemoveEmptyEntries);
You can use a regex for extracting file names if you do not have any other clear way to do that. Can you try the code below ?;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExtensionExtractingTest
{
class Program
{
static void Main(string[] args)
{
string fileNames = "test.docxtest2.txttest3.pdftest.test.xlxtest.docxtest2.txttest3.pdftest.test.xlxtest.docxtest2.txttest3.pdftest.test.xlxourtest.txtnewtest.pdfstackoverflow.pdf";
//Add your extensions to regex definition
Regex fileNameMatchRegex = new Regex(#"[a-zA-Z0-9]*(\.txt|\.pdf|\.docx|\.txt|\.xlx)", RegexOptions.IgnoreCase);
MatchCollection matchResult = fileNameMatchRegex.Matches(fileNames);
List<string> fileNamesList = new List<string>();
foreach (Match item in matchResult)
{
fileNamesList.Add(item.Value);
}
fileNamesList = fileNamesList.Distinct().ToList();
Console.WriteLine(string.Join(";", fileNamesList));
}
}
}
And a working example is here http://ideone.com/gbopSe
PS: Please keep in mind you have to know your file name extensions or you have to predict filename extension length 3 or 4 and that will be a painful string parsing operation.
Hope this helps

What is the Most Efficient way to Place Strings to Array from .txt

I have a text file with about 30 words (of varying length). I'm trying to bring all of those words into the program and store them into an array of 'x' elements (x being the number of words).
Any help? I'm literally on day 2 of learning.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman {
class Program {
static void Main(string[] args) {
//StreamReader myWordList = new StreamReader("WordList.txt");//string stringArray[] = StreamReader(WordList.txt);//.WordList.txt;
String myWordArrays[] = File.ReadAllLines(#
"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman");
Console.WriteLine(myWordArrays[2]);
Console.ReadLine();
}
}
}
This is the complete code (above) - I'm getting these errors:
Error 1 Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 32 Hangman
And
Error 2 Invalid expression term '=' c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 35 Hangman
I don't really understand that, because I'm calling it like I should be (or so I would think? o.0)
And this:
Error 3 ; expected c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 35 Hangman
also this one
Error 4 ; expected c:\users\youtube upload\documents\visual studio 2013\Projects\Hangman\Hangman\Program.cs 16 37 Hangman
Forgive my horrible formatting here - I'm new to this site and am just getting used to it all. :(
Get values from file like this :
string[] myWordArrays = File.ReadAllLines(#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\yourfilename");
Your whole program :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman {
class Program {
static void Main(string[] args) {
string[] myWordArrays = File.ReadAllLines(#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\yourfilename");
Console.WriteLine(myWordArrays[2]);
Console.ReadKey();
}
}
}
P.S. What mistakes have you made in this line of code
String myWordArrays[] = File.ReadAllLines(#
"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman\");
Incorrect variable declaration. Correct one is
string[] myWordArrays = ...
'#' sign should be placed right before string that contain escape characters and should be on a same line. What if line is too long? Then you can move both this sign and the string to a next line.
string[] myWordArrays = File.ReadAllLines(
#"C:\Users\YouTube Upload\Documents\Visual Studio 2013\Projects\Hangman");
File.ReadAllLines method accepts only full path and not a relative one. To point to a file that is located in the same folder where executive file is stored (bin folder) you can use Directory.GetCurrentDirectory() method. So you can change it to :
string filename = 1.txt;
File.ReadAllLines(Directory.GetCurrentDirectory() + "\" + filename);
Depending on the character(s) used to split the strings, you could use one of the following:
var streamReader = new StreamReader("file");
var words = streamReader.ReadToEnd();
var wordArray = words.Split(new[] { Environment.NewLine }, StringSplitOptions.None); // For words split by lines where you know the format of the line ending
var wordArray = words.Split(new [] {"\n", "\r\n"}, StringSplitOptions.None); // For words split by lines where the format could be unix or windows
var wordArray = words.Split(','); // For words split by comma
So, for more explination StreamReader.ReadToEnd() returns a string. This class has many methods as defined in:
https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx
These methods include a "split" method, which takes either an array of characters (or multiple comma separated characters) (char denoted by single quote (')) or an array of strings with string split options.
In the latter, we define a new array of strings with new [] { "string1", "string2", "..."} here the type of the array is implicit, but we could specify new string[] {...} if we wanted, or pass in an array of strings we had already defined. The second option is an enum with two values; None and RemoveEmptyEntries, which are defined here:
https://msdn.microsoft.com/en-us/library/system.stringsplitoptions(v=vs.110).aspx
There are additional overloads for the string.split method (which are in the top link).
I would like to thank all of you for the tremendous help. I had the formatting incorrect, but I guess I understood how it worked after all!! lol. At least it wasn't a misplaced/missing semicolon, yeah? :)
namespace Hangman
{
class Program
{
static void Main(string[] args)
{
//StreamReader myWordList = new StreamReader("WordList.txt");//string stringArray[] = StreamReader(WordList.txt);//.WordList.txt;
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Console.WriteLine(myWordArrays[2]);
Console.ReadLine();
}
}
}
Thank you all so very much. This fixed it, and it did successfully display the 3rd element (string), which is advice, which happens to be on the third line [2] - perfect. Thank you!!!
Try this, it may help you.
private void PutTextIntoArray()
{
var array = ReadTextFile("C:\\WordList.txt").GetTotalWords();
}
private static string ReadTextFile(string file)
{
try
{
return File.ReadAllText(file);
}
catch (IOException ex)
{
return ex.Message;
}
catch (Exception ex)
{
return ex.Message;
}
}
public static class Extensions
{
public static string ReplaceMultipleSpacesWith(this string text, string newString)
{
return Regex.Replace(text, #"\s+", newString);
}
public static string[] GetTotalWords(this string text)
{
text = text.Trim().ReplaceMultipleSpacesWith(" ");
var words = text.Split(' ');
return words;
}
}

How to read character in a file 1 by 1 c#

I want my program to read a text file all characters 1 by 1 and whereever it finds a double-quote ("), it adds a semicolon before that inverted comma. For eg we have a paragraph in a text file as follow:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name "Sam" i was born at "12:00" "noon". I live in
"anyplace" .
Now I want the output to be as follows:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name ;"Sam;" i was born at ;"12:00;" ;"noon;". I
live in ;"anyplace;" .
It should open the file using file stream then reads character and then adds semicolon where it finds quotes. And the output should be equal to textbox1.Text.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char ch;
int Tchar = 0;
StreamReader reader;
reader = new StreamReader(#"C:\Users\user1\Documents\data.txt");
do
{
ch = (char)reader.Read();
Console.Write(ch);
if (Convert.ToInt32(ch) == 34)
{
Console.Write(#";");
}
Tchar++;
} while (!reader.EndOfStream);
reader.Close();
reader.Dispose();
Console.WriteLine(" ");
Console.WriteLine(Tchar.ToString() + " characters");
Console.ReadLine();
}
}
}
This is the output:
This is a paragraph which conains lots and lots of characters and some
names and dates. My name ";Sam"; i was born at ";12:00"; ";noon";. I
live in ";anyplace"; . 154 characters
I want that semicolon before the quotes. Any help would be appreciated. Thanks!
Swap the order of the operations:
if (Convert.ToInt32(ch) == 34)
{
Console.Write(#";");
}
Console.Write(ch);
e.g. don't write the original character until AFTER you've decided to output a semicolon or not.
Try ch = (char)reader.Peek();
This will read tell you the next character without reading it. You can then use this to check if it is a " or not an insert : accordingly
if (Convert.ToInt32((char)read.Peek()) == 34) Console.Write(#";")
Do you have to read in character by character? The following code will do the whole thing as a block and return you a list containing all your lines.
var contents = File.ReadAllLines (#"C:\Users\user1\Documents\data.txt")
.Select (l => l.Replace ("\"", ";\""));
using System;
using System.IO;
using System.Text;
namespace getto
{
class Program
{
static void Main(string[] args)
{
var path = #"C:\Users\VASANTH14122018\Desktop\file.v";
string content = File.ReadAllText(path, Encoding.UTF8);
Console.WriteLine(content);
//string helloWorld = "Hello, world!";
foreach(char c in content)
{
Console.WriteLine(c);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}

Categories