C# string

C3 strings
C# string is a object of class String. Value of string is text, which is nothing
but the collections of read-only char Objects. In C# we can do various string operations like
strings splitting, string indexOf, string reverse, string format , we can also use string .ToUpper()
to make string in upper case in C#, also we can use string .ToLower() to make string in
lower case in C#. String also has Trimmimg functions. we can trim the string in
c# using these functions. We will discuss most of these function to perform operations
on string using c#.

C# string is alias for System.String so String and string are equivalent
to each other. The Length property of string shows number of char objects
the string contains. C# string provides lot’s of methods to create and to manipulate,
to compare, to split…etc.


C# string is immutable, means we can not change contents of string once object
is get created. When ever we change the contents of string new object of string
get created. We will see examples of c# string operations and manipulations. Below
samples will show how to make string in upper case in c# and how to make string
in lower case.

1. ToUpper() method is used to convert string in upper case.

Sample code to shows how to convert string to upper case[c#]


string myString = "This is C# string" 
string toUpperString = myString.ToUpper(); 

2. ToLower() method is used to convert string in lower case. Below example
shows how to convert string in lower case:


string myString = "This is C# string"
string tolowerString = myString.ToLower();


3. Trim() method is used to remove all white spaces from both start and end
of the string. 

string myString = " This is C# string "
string trimedString = myString.Trim();

TrimStart() method is used to trim string at start of string and TrimEnd()
is used to trim the string at the end.

TrimStart() C# example:


string myString = " This is C# string ";
string trimedString = myString.TrimStart();

TrimEnd() C# example:


string myString = " This is C# string " ;
string trimedString = myString.TrimEnd(); 

We can strip out specified characters from start of the string or at the end of
the string. Example below shows how to strip out characters from start and end position
TrimSart() C# example:


string myString = " This is C# string "; string 
trimedString = myString.TrimStart(); 
4. Replace() function used to replace string/char from the given string.

string myString = "This is VB string";
string newString = myString.Replace(“VB”, “C#”);


//Above line of code will replace “VB” by “C#”. 

5. Split() function used to split the string by the specified char and stores
it in array. Below code will split string by “,” and will store result in array
of string. Splitting a string into substrings—such as splitting a sentence into
individual words—is a common programming task. The Split() method takes a char array
of delimiters, for example, a space character, and returns an array of substrings.


string myString = "C#,VB,ASP.NET,C++";
string[] splitedString = myString.Split(‘,’); 

6. ToString() method provided by string class converts a value to a string.
Below C# code shows how .ToString() will convert numeric values into string:


int year = 1999;
string msg = year.ToString();

7. Substring() Function finds the specified characters form the string starts from 0 of the string to the used position. Substring functions takes integer parameter, which specifies from what position we need to substring the string. Below Substring sample code shows how to get substring from 8th position till end:


string myString = " This is C# string "
string newSubString = myString.Substring(8);

So result of substring of above code will take string “C# string”. We can also specify
the range from which position to which position we need to get substring.

Example below how Substring() works in c#:


string myString = " This is C# string ";
string newSubString = myString.Substring(8, 2);
Result of above code will be string “C#”. 

8.IndexOf() function is used to find String within string and returns index
position of the string. If specified character or string has not found in string
then it returns -1 index.


string myString = " This is C# string ";
int newSubString = myString.IndexOf (“C#”);
Above code will return 8th index position.

9. ToCharArray() Copies the characters in this instance to a Unicode character
array. We can use then this array to reverse the string.Below is the C# code to
Reverse the string


string myString = "string";
char[] stringArray = myString.ToCharArray();
Array.Reverse(stringArray);
string
newString = new string(stringArray);


Result of above code is “gnirts”.

Concatenate strings:In C# we can "add" two strings of text together
to create one string. The process of adding two strings together is called string
concatenation.


string s1 = "Learn C# ";
string s2 = "Strings";
string newString = s1 + s2;
So newString will hold the concatenated string “Learn C# Strings”.

The @ SymbolThe @ symbol tells the string constructor to ignore
escape characters and line breaks. The following two strings are therefore identical:

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @\\My Documents\My Files\

embed resources like .js, .css or images in c#

C# embedded .js, .css , image resources

In this post we will learn how to embed the resources like javascript file, images, .css files in class libraries. When creating custom controls sometimes we need to provide resources like .js, .css and images along with control or class library assembly.


Below are the step by step example of how to embed .js file as resource and access it using WebResource.axd.

1. In Visual Studio, create a new project with selection as class library project. And Name it as ImageControl.

2. Add references like System.Web, System.Web.UI, System.Web.UI.WebControls..etc which are you think you need for creating controls.

3. Add image file e.g. image1.gif, then right click on image, go to properties and setBuild Action to Embedded Resource. Setting build action to embeddedd resource is important part while embedding resources in controls or in class libraries.

4. If you want javascript file in class library as embedded resource then add .js file e.g. script1.js in the project then add some code to it like:

function ClickMe() 

{
  alert("Hey, I get called by embedded js and I am available through web resources");
} 


5. Now next step is to right click on js file go to properties and set it's Build Action to Embedded Resource. As mentioned above it is important to set action build to embedded resource in controls or in class libraries.

6. Now add one style1.css file in project and follow the same steps to make it embedded resource like right click on css file, goto it's properties and set it's Build Action to Embedded Resource.
e.g.:
body
{
 font-family:Verdana;font-size:x-large;font-weight:bolder;color:Blue;
}

7. In order to access these embedded resource files we can use WebResource. For that we need to do one important thing that we need to add WebResources properties in assemblyinfo.cs of class library or on the class libary page itself just before namespace starts lik:
In AssemblyInfo.cs of the projects properties folder add some think like below at the end of the file.

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]


Here in ImageControl.Scripts.script1.js, ImageControl is the assembly name, Scripts is the folder in which we keep the and after that javascript file name. And is same for other resources.

8. Now to refer these resouces in control we need to do following things.
a. To refer .js file we may do like below in the controls code:

string jsResource = "ImageControl.Scripts.script1.js"; this.Page.ClientScript.RegisterClientScriptResource (this.GetType(), jsResource);

b. To refer to image file we can do like:

Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.ImageHolder), ImageControl.Images.image1.gif"));

c. To refer to .css file we need to do like:
string cssResource = "ImageControl.Css.script1.css";
string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);

And in order to add it like

HtmlLink cssLink = new HtmlLink();
 cssLink.Href = cssResourceURL;
 cssLink.Attributes.Add("rel", "stylesheet");
 this.Page.Header.Controls.Add(cssLink);
 

Below id the sample that creates Image control in which we have image, .js and .css as embedded resources. And we are accessin it using WenResource.axd.

using System;
using System.Web.UI.WebControls;
using System.Web.UI;

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]

namespace ImageControl
{
    public class ImageHolder : Image
    {
        protected string _message;
        protected string _toolTip;
        protected bool _showBigIcon = true;
        public ImageHolder()
        {
        }
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src,
            Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.
            ImageHolder), "ImageControl.Images.image1.gif"));
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "ClickMe()");
            writer.AddAttribute(HtmlTextWriterAttribute.Alt,
            "I am embedded Image and you are watching me from Web Resource");
            base.AddAttributesToRender(writer);
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string jsResource = "ImageControl.Scripts.script1.js";
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(),
            jsResource);
            //To add the CSS file to the custom control
            string cssResource = " ImageControl.Css.style1.css";
            string cssResourceURL = Page.ClientScript.GetWebResourceUrl
            (this.GetType(), cssResource);
            HtmlLink cssLink = new HtmlLink();
            cssLink.Href = cssResourceURL;
            cssLink.Attributes.Add("rel", "stylesheet");
            this.Page.Header.Controls.Add(cssLink);
        }
    }
}


Now to test our Image Control and embedded resources we need to add reference of class library project or dll and need to set below things in Web Project.

1. In web .config add below lines of code :
<pages>
<controls>
<add namespace="ImageControl" assembly="ImageControl" tagPrefix="myImage"/>
</controls>
</pages>
<add assembly="ImageControl" namespace="ImageControl" tagprefix="myImage" />
</controls></pages>
2. And In aspx page
3. < myImage:ImageHolder ID="img1" runat="server"/>

After running code we will get image displayed on page which is embedded and also calls javascript function for embedded .js and will show font that set in embedded .css file on the control.