Skip to content

Instantly share code, notes, and snippets.

@Curtis-64
Last active January 25, 2024 17:16
Show Gist options
  • Save Curtis-64/a34b21e7b212991042fd6cba3baf472a to your computer and use it in GitHub Desktop.
Save Curtis-64/a34b21e7b212991042fd6cba3baf472a to your computer and use it in GitHub Desktop.
ReplaceStringExamples
Replace String Examples C# by Hacker Gnome GPT / Curtis White, Senior Software Engineer, Prompt Engineer
Not tested
Concise #1
string result = lines.Replace("\r\n", "\n");
Concise #2
GPT
The performance benefit of using regular expressions can be realized when the Regex object is compiled once and used multiple times, especially on very large strings. However, for single replacements on small to moderately sized strings,
the difference in performance may not be significant compared to the concise solution. ?
using System.Text.RegularExpressions;
string result = Regex.Replace(lines, "\r\n", "\n");
String Builder #3
var builder = new StringBuilder(lines.Length);
string[] linesArray = lines.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (var line in linesArray)
{
builder.Append(line).Append('\n');
}
// Remove the last '\n' if it was added unnecessarily
if (lines.EndsWith("\r\n"))
{
builder.Length--;
}
string result = builder.ToString();
Straming #3
using System;
using System.IO;
using System.Text;
public static void ConvertLineEndings(Stream inputStream, Stream outputStream)
{
using (var reader = new StreamReader(inputStream))
using (var writer = new StreamWriter(outputStream))
{
char prevChar = '\0';
while (reader.Peek() >= 0)
{
char c = (char)reader.Read();
if (c == '\n' && prevChar == '\r')
{
// If the previous character was '\r' and the current is '\n',
// write only '\n' (effectively replacing "\r\n" with "\n").
writer.Write(c);
}
else if (prevChar == '\r')
{
// If the previous character was '\r' but the current is not '\n',
// write out the '\r' as it was not part of a "\r\n" sequence.
writer.Write(prevChar);
writer.Write(c);
}
else if (c != '\r')
{
// If the current character is not '\r', write it out.
writer.Write(c);
}
// Update the previous character.
prevChar = c;
}
// Handle the case where the last character in the stream is '\r'.
if (prevChar == '\r')
{
writer.Write('\n');
}
writer.Flush();
}
}
// Usage example:
// Open the input stream and output stream for the data you want to process.
// ConvertLineEndings(inputStream, outputStream);
Streaming #4
using System;
using System.IO;
using System.Threading.Tasks;
public static async Task ConvertLineEndingsAsync(Stream inputStream, Stream outputStream)
{
byte[] buffer = new byte[8192]; // 8 KB buffer
int bytesRead;
bool lastCarriageReturn = false;
while ((bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
int writeIndex = 0;
for (int i = 0; i < bytesRead; i++)
{
if (buffer[i] == '\r') // Carriage return found
{
lastCarriageReturn = true;
}
else
{
if (buffer[i] == '\n') // Line feed found
{
if (!lastCarriageReturn) // If not preceded by '\r', write it
{
buffer[writeIndex++] = buffer[i];
}
}
else // Any other character
{
if (lastCarriageReturn) // If preceded by '\r', write it now
{
buffer[writeIndex++] = (byte)'\r';
}
buffer[writeIndex++] = buffer[i];
}
lastCarriageReturn = false;
}
}
await outputStream.WriteAsync(buffer, 0, writeIndex);
}
if (lastCarriageReturn) // Handle trailing '\r'
{
await outputStream.WriteAsync(new byte[] { (byte)'\n' }, 0, 1);
}
}
// Usage example:
// Open the input stream and output stream for the data you want to process.
// await ConvertLineEndingsAsync(inputStream, outputStream);
In this optimized solution:
A fixed-size buffer is used to read and write data, which is more efficient than character-by-character operations.
In-place replacement within the buffer is performed, which minimizes the memory footprint.
Asynchronous methods ReadAsync and WriteAsync are used for I/O operations, improving overall efficiency, especially in I/O-bound environments.
This code is designed to be integrated into an application where asynchronous operations are beneficial and expected. It provides an efficient way to process large data streams with minimal memory overhead and is optimized for both performance and brevity.
RubeGoldBergSolution TESTED
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class RubeGoldbergStringProcessor
{
public string OverlyComplexLineEndingConversion(string lines)
{
// Stage 1: Encode the string into a series of ASCII values.
var asciiEncoded = lines.Select(c => (int)c).ToList();
// Stage 2: Map ASCII values to a pseudo-binary representation.
var pseudoBinary = asciiEncoded.Select(n => Convert.ToString(n, 2)).ToList();
// Stage 3: Pair the binary representations with their original characters.
var pairedList = lines.Zip(pseudoBinary, (c, b) => new { Char = c, Binary = b }).ToList();
// Stage 4: "Compress" the data by converting the binary back to integers.
var compressedData = pairedList.Select(p => Convert.ToInt32(p.Binary, 2)).ToList();
// Stage 5: Identify the \r\n sequences by their ASCII values (13 and 10).
var lineEndingPairs = compressedData.Select((value, index) => new { Value = value, Index = index })
.Where(x => x.Value == 13 && compressedData.ElementAtOrDefault(x.Index + 1) == 10)
.Select(x => x.Index).ToList();
// Stage 6: Remove the identified \r (ASCII 13) from the compressed data.
foreach (var index in lineEndingPairs.OrderByDescending(i => i))
{
compressedData.RemoveAt(index);
}
// Stage 7: "Decompress" the data by converting ASCII values back to characters.
var decompressedData = compressedData.Select(i => (char)i).ToList();
// Stage 8: Reconstruct the string, ensuring to skip over any remaining \r characters.
var reconstructedString = new string(decompressedData.Where(c => c != '\r').ToArray());
return reconstructedString;
}
public static void Main()
{
var originalString = "test1\r\ntest2\r\ntest3";
RubeGoldbergStringProcessor processor = new RubeGoldbergStringProcessor();
string result = processor.OverlyComplexLineEndingConversion(originalString);
System.Console.WriteLine(result);
}
}
Smirk Wiping Solution
using System;
public static class SmirkWipingStringReplacer
{
public static string ReplaceLineEndings(ReadOnlySpan<char> input)
{
Span<char> buffer = stackalloc char[input.Length];
int bufferIndex = 0;
for (int i = 0; i < input.Length; ++i)
{
if (input[i] == '\r' && i + 1 < input.Length && input[i + 1] == '\n')
{
continue; // Skip the '\r'
}
buffer[bufferIndex++] = input[i];
}
return new string(buffer.Slice(0, bufferIndex));
}
public static void Main()
{
var originalString = "Look at this Python! \r\nC# can be pretty cool too.\r\n";
var result = ReplaceLineEndings(originalString.AsSpan());
Console.WriteLine(result);
}
}
// To execute the Main method, compile the code and run the resulting executable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment