Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Friday, 16 December 2011

C# String Functions and Manipulation

C# and VB.NET have a whole set of string functions to trim, find, search, replace and split strings. It's also simple to convert to upper case or title case

Trim Function


The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimEnd


TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

//STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimStart


TrimStart is the same as TrimEnd apart from it does it to the start of the string.

//STRIPS CHRS FROM THE START OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','S'};
string NewName = Name.TrimStart(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

Find String within string


This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
//SHOWS START POSITION OF STRING
MessageBox.Show("Found at : " + FirstChr );

Replace string in string


Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString "String Manipulatin";
string CorrectString = MainString.Replace("Manipulatin", "Manipulation");
//SHOW CORRECT STRING
MessageBox.Show("Correct string is : " + CorrectString);

Strip specified number of characters from string


This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = "S1111tring Manipulation";
string NewString = MainString.Remove(1,4);


//SHOW OUTPUT
MessageBox.Show(NewSring);

Split string with delimiter


The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = "String Manipulation";
string [] Split = MainString.Split(new Char [] {' '});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));

Convert to title (proper) case


This is a simple extension method to convert a string to Proper Case or Title Case (ie the first character of each word is made upper case).
public static string ToTitleCase(this string title)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
return textInfo.ToTitleCase(title);
}

Convert Xml document to String

    Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server" Mode="Encode"></asp:Literal></div>
</form>
</body>
</html>

Default.aspx.cs :

using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<deneme/>");
#region just to remind myself something
XmlNode node = doc.CreateElement("serkan");
doc.DocumentElement.AppendChild(node);
#endregion
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
// i use literal control because when you set its mode to "encode", you can write xml tags to browser window as they are
Literal1.Text = sw.ToString();

}
}

Different ways how to escape an XML string in C#

Different ways how to escape an XML string in C#


XML encoding is necessary if you have to save XML text in an XML document. If you don't escape special chars the XML to insert will become a part of the original XML DOM and not a value of a node.

Escaping the XML means basically replacing 5 chars with new values.

These replacements are:




























<->&lt;
>->&gt;
"->&quot;
'->&apos;
&->&amp;

 

Here are 4 ways you can encode XML in C#

1. string.Replace() 5 times

This is ugly but it works. Note that Replace("&", "&amp;") has to be the first replace so we don't replace other already escaped &.

 
string xml = "<node>it's my \"node\" & i like it<node>";
encodedXml = xml.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;

 

 

2. System.Web.HttpUtility.HtmlEncode()

Used for encoding HTML, but HTML is a form of XML so we can use that too. Mostly used in ASP.NET apps. Note that HtmlEncode does NOT encode apostrophes ( ' ).
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = HttpUtility.HtmlEncode(xml);

// RESULT: &lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;

3. System.Security.SecurityElement.Escape()

In Windows Forms or Console apps I use this method. If nothing else it saves me including the System.Web reference in my projects and it encodes all 5 char.


string xml = "<node>it's my \"node\" & i like it<node>";

string encodedXml = System.Security.SecurityElement.Escape(xml);

 

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;



4. System.Xml.XmlTextWriter

Using XmlTextWriter you don't have to worry about escaping anything since it escapes the chars where needed. For example in the attributes it doesn't escape apostrophes, while in node values it doesn't escape apostrophes and qoutes.



string xml = "<node>it's my \"node\" & i like it<node>";

using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))

{

xtw.WriteStartElement("xmlEncodeTest");

xtw.WriteAttributeString("testAttribute", xml);

xtw.WriteString(xml);

xtw.WriteEndElement();

}

 

// RESULT:

/*

<xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;">

&lt;node&gt;it's my "node" &amp; i like it&lt;node&gt;

</xmlEncodeTest>

*/



 

Each of the four ways is different, so use each one where you fell appropriate. You can't go wrong with SecurityElement though. :)