29. Oktober 2011

C# Whitespace Tips - String Modifications


As part of the coverage of strings in the C# language, we focus on custom whitespacemethods, which help us modify space and newline characters in string data. Also, some of these methods can be used with non-whitespace characters, but typically are used with spaces and newlines.
Key points:Whitespace characters can be converted with the methods shown here. It is useful to convert from Windows and UNIX newlines in some situations.

Condense whitespace

Here, we see how you can use the static Regex.Replace method to change any of a set of individual characters to a space. The square brackets [ ] in the parameter indicate a set of separate characters. To use this example, you will need to add "using System.Text.RegularExpressions;" to the top of your .cs file.
Regex.Replace Examples: MatchEvaluator
Method that uses Regex.Replace [C#]

/// 
/// Converts all whitespace in the string to spaces using Regex.
/// 
public static string ConvertWhitespaceToSpacesRegex(string value)
{
    value = Regex.Replace(value, "[\n\r\t]", " ");
    return value;
}

Replace line break chars

You can also replace all line breaks in your string using two string Replace calls. These receive a single character as the parameters. The first parameter is the character you need to replace, and the second character is the replacement. When using the char overload, you cannot replace a character with nothing.
Replace String Examples
Method that uses string Replace [C#]

/// 
/// Converts all whitespace in the string to spaces using string Replace.
/// 
public static string ConvertWhitespaceToSpacesString(string value)
{
    value = value.Replace('\r', ' ');
    value = value.Replace('\n', ' ');
    return value;
}

Convert whitespaces

Conversion or change
The method you see here uses the ToCharArray method on the string parameter, which converts the string to a char[] array. This allows us to modify the characters in-place. The result is that the performance of this method is far better than those that use Replace calls, on small strings.
ToCharArray Method, Convert String to Array
Method that uses ToCharArray and switch [C#]

/// 
/// Converts all the whitespace in the string to spaces using switch.
/// 3-4x faster than using string replace.
/// Faster than using a new empty array and filling it.
/// 
public static string ConvertWhitespaceToSpaces(string value)
{
    char[] arr = value.ToCharArray();
    for (int i = 0; i < arr.Length; i++)
    {
 switch (arr[i])
 {
     case '\t':
     case '\r':
     case '\n':
  {
      arr[i] = ' ';
      break;
  }
 }
    }
    return new string(arr);
}
Switch statement. Internally, this method uses a switch on the char, which is compiled to a jump table. Jump tables are low-level instructions that provide constant lookup time. Therefore, the switch is faster than if/else statements.
Switch Char, Conditional Character TestSwitch Enum

Newline to spaces

Here we see a method that converts all Windows newlines, which contain two characters, and all UNIX newlines, which contain one character. The newlines are all converted to single spaces. The clever part of this method is that it converts the Windows newlines first.
Method that replaces newlines [C#]

/// 
/// Converts all newlines in the string to single spaces.
/// 
public static string ConvertNewlinesToSingleSpaces(string value)
{
    value = value.Replace("\r\n", " ");
    value = value.Replace('\n', ' ');
    return value;
}
Question mark
Why convert Windows newlines first? The reason you must convert the two-character Windows line breaks first is that the UNIX newlines are half of the Windows ones. Therefore, if you replace UNIX newlines first, you will be left with '\r' characters you don't want.

UNIX newlines

It is very easy to convert all linebreaks in a string you read in from the disk. On the string, simply use Replace to change all Windows newlines to UNIX newlines. You do not need to change any existing UNIX newlines.
Method that converts to UNIX newlines [C#]

/// 
/// Converts Windows style newlines to UNIX-style newlines.
/// 
public static string ConvertToUnixNewlines(string value)
{
    return value.Replace("\r\n", "\n");
}

Windows newlines

You can also convert all the newlines in your string to Windows newlines, providing compatibility with many applications. The trick here is to convert all pre-existing Windows newlines to UNIX newlines first. Then, convert all UNIX newlines to Windows newlines.
Method that converts to Windows newlines [C#]

/// 
/// Converts all newlines in the file to Windows newlines.
/// 
public static string ConvertToWindowsNewlines(string value)
{
    value = ConvertToUnixNewlines(value);
    value = value.Replace("\n", "\r\n");
    return value;
}
Description. The code example uses the ConvertToUnixNewlines method in the section directly above. You could simply paste the Replace call instead of using that method.

Replace many whitespaces

Here we see a method that converts any number of whitespaces in a sequence into a single space. This is really useful for when you are reading in text data from a database or file and are not sure what kind of whitespaces are used in it.
Method that uses Regex.Replace [C#]

/// 
/// Convert all whitespaces to a single space.
/// 
public static string ConvertWhitespacesToSingleSpaces(string value)
{
    value = Regex.Replace(value, @"\s+", " ");
    return value;
}
Using this method with HTML. Sometimes, you can use this method on markup such as HTML to reduce the size of the file. My experience is that this can reduce the final size by 1%, even after compression. In HTML, two spaces are usually the same as one space.

Whitespace in file

This example uses the simple File.ReadAllText method and calls one of the above methods. Note that the example has the "using System.IO;" line near the top. It writes the modified file, TextFile1.txt, to the Console window. The NewlineTool class specified is a static class located in another file. You can create it by creating "NewlineTool.cs" and then looking at the next example and using the code there.
File.ReadAllText (TXT)
Method that uses File.ReadAllText [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
 //
 // Read in text with File.ReadAllText.
 //
 string value = File.ReadAllText("TextFile1.txt");
 //
 // Call method and display result.
 //
 value = NewlineTool.ConvertWhitespacesToSingleSpaces(value);
 Console.WriteLine(value);
 //
 // You can now write it with File.WriteAllText.
 //
    }
}

Static whitespace class

I prefer to keep static methods, which do not require allocation or state, in a separate file. The file should have the name of its class as the filename. The class must also be public, as well as the individual methods.
Static Class
Example of static class [C#]

using System.Text.RegularExpressions;

/// 
/// Contains string methods for converting newlines.
/// 
public static class NewlineTool
{
    /// 
    /// Converts all whitespace in the string to spaces using Regex.
    /// 
    public static string ConvertWhitespaceToSpacesRegex(string value)
    {
 // ...
    }
}

Summary

We explored whitespace handling in the C# language. We saw ways to convert newlines, line breaks, spaces, tabs and all whitespace characters into single spaces or other characters; we also looked at UNIX newlines and Windows newlines, and how to Replace these strings.
String Type

26. Oktober 2011

Terrashop - PHP Profi-Paket um 19,99 € (Normalpreis 99,95 €)


 
Ausgabe vom 26.10.2011      
Bild der Woche

Es gibt viele neue Angebote zu entdecken. Das Highlight für Programmierer ist unser neues PHP Profi-Paket, bestehend aus 3 Büchern mit insgesamt über 1.500 Seiten Know-how.

PHP Profi-Paket - 3 Bücher statt 99,95 EUR nur 19,99 EUR


Unser besonderer Tipp ist der 1GB-Mini-USB-Stick mit Synchro Pro Software, statt 49,95 EUR bekommen Sie diesen bei uns jetzt mit 90% Rabatt!

1GB Mini-USB-Stick inkl. Synchro Pro für 4,99 EUR

Mit freundlichen Grüßen

Helmut Frey
Geschäftsführer terrashop.de

PHP Profi-Paket
[Bild]
3 Bücher, die Sie zum PHP-Profi machen! Jetzt im Bundle zum Vorzugspreis - Nur solange der Vorrat reicht.

Franzis, 3 Bücher im Bundle
Früher 99,95 €*, bei uns nur 19,99 €

[Bild]
Die schnelle Praxisreferenz. Dieses Nachschlagewerk macht Sie fit für die Programmierung mit PHP. Kompakte Beispiele vermitteln Ihnen praxisgerecht alles, was Sie für den Effizienten Einsatz von PHP 5 brauchen.

Jens Ferner - Data Becker, 448 Seiten
Früher 17,95 €*, bei uns nur 4,99 €