The following code example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.
C#
==
// This code example demonstrates the String.Format() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
{
// Store the output of the String.Format method in a string.
string s = "";
Console.Clear();
// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
s = String.Format(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
Console.WriteLine(s);
// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
s = String.Format(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal sortable: . . . {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
Console.WriteLine(s);
// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
s = String.Format(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
Console.WriteLine(s);
}
}
This code example produces the following results:
=================================================
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal sortable: . . . Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
(Y) String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);
(Y) This will output “$1,240.00″ if passed 1243.50. It will output the same
format but in parentheses if the number is negative, and will output
the string “Zero” if the number is zero.
Monday, August 10, 2009
Useful Techniques in Asp.Net
1. Finding the particular Data from the Dataset,Its Row Position and Current Page in Grid
====================================================================================
DataSet dsQuoteList = objQuote.GetQuoteBankList();
Giving a constraints to the first column that is the ID primary key like:
dsQuoteList.Tables[0].Constraints.Add("pk", dsQuoteList.Tables[0].Columns[0], true);
Now,
The below code will find the perticular ID int the given dataset and return new Datarow..
DataRow dr = dsQuoteList.Tables[0].Rows.Find("10540");
Now finding the Row position (RowIndex) in the Dataset, like..:
int RowIndx = int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()
Finally, You will get the exact position of particular Data in the Dataset.
In Addition You can also find the Current Page in the Datagrid or GridView after getting Datarow:
int PageSize = 10;
double CurrPage = Math.Ceiling(Convert.ToDouble(int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()) / PageSize ));
Done..
That's it !
2. Find the Exact words from string
==================================
using System.Text;
using System.Text.RegularExpressions;
Write in the Button Click Event :
private void button1_click(object sender, EventArgs e)
{
string strInput = "Hello World I am Here with the new sunrise";
string strOutput = FindFirstWords(strInput, 4);
// Here the result of strOutput variable is : Hello World I am
}
Function to get the Words from string:
private string FindFirstWords(string input, int HowManyFind)
{
string REGEX = @"([\w]+\s+){" + HowManyFind + "}";
StringBuilder output = new StringBuilder();
foreach (Capture capture in Regex.Match(input, REGEX).Captures)
{
output.Append(capture.Value);
}
return output.ToString();
}
3. foreach loop in Enum
==================================
objDataImport = new DataImport();
foreach (string s in Enum.GetNames(typeof(DataImport.eTotalFeature)))
{
objDataImport.CurrentFeature = (DataImport.eTotalFeature)Enum.Parse(typeof(DataImport.eTotalFeature), s);
objDataImport.FetchContent();
}
4. Read line by line from text file in C#
==========================================
string strFile = @"C:\Files\new.txt";
StreamReader objStreamReader = File.OpenText(strFile);
string strGetLine;
while ((strGetLine = objStreamReader.ReadLine()) != null)
{
Response.Write(strGetLine);
}
How to download any file with Asp.Net
=================================
string FileName = Server.MapPath("style.css").ToString();
Response.Clear();
Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=Name.css;");
byte[] buffer = System.IO.File.ReadAllBytes(FileName);
System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);
mem.WriteTo(Response.OutputStream);
Response.End();
Render GridView to Html String
==========================
In many times I have faced a problem when you want to
render html string for GridView Control, but you
probably find error like...
"Control '' of type 'GridView' must be placed inside a form tag with runat=server."
In this case you have to use one method to avoid this error..
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
// specified ASP.NET server control at run time.
// No code required here.
}
and in the page directives just add this code marked in Bold Text..
====================================================================================
DataSet dsQuoteList = objQuote.GetQuoteBankList();
Giving a constraints to the first column that is the ID primary key like:
dsQuoteList.Tables[0].Constraints.Add("pk", dsQuoteList.Tables[0].Columns[0], true);
Now,
The below code will find the perticular ID int the given dataset and return new Datarow..
DataRow dr = dsQuoteList.Tables[0].Rows.Find("10540");
Now finding the Row position (RowIndex) in the Dataset, like..:
int RowIndx = int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()
Finally, You will get the exact position of particular Data in the Dataset.
In Addition You can also find the Current Page in the Datagrid or GridView after getting Datarow:
int PageSize = 10;
double CurrPage = Math.Ceiling(Convert.ToDouble(int.Parse(dsQuoteList.Tables[0].Rows.IndexOf(dr).ToString()) / PageSize ));
Done..
That's it !
2. Find the Exact words from string
==================================
using System.Text;
using System.Text.RegularExpressions;
Write in the Button Click Event :
private void button1_click(object sender, EventArgs e)
{
string strInput = "Hello World I am Here with the new sunrise";
string strOutput = FindFirstWords(strInput, 4);
// Here the result of strOutput variable is : Hello World I am
}
Function to get the Words from string:
private string FindFirstWords(string input, int HowManyFind)
{
string REGEX = @"([\w]+\s+){" + HowManyFind + "}";
StringBuilder output = new StringBuilder();
foreach (Capture capture in Regex.Match(input, REGEX).Captures)
{
output.Append(capture.Value);
}
return output.ToString();
}
3. foreach loop in Enum
==================================
objDataImport = new DataImport();
foreach (string s in Enum.GetNames(typeof(DataImport.eTotalFeature)))
{
objDataImport.CurrentFeature = (DataImport.eTotalFeature)Enum.Parse(typeof(DataImport.eTotalFeature), s);
objDataImport.FetchContent();
}
4. Read line by line from text file in C#
==========================================
string strFile = @"C:\Files\new.txt";
StreamReader objStreamReader = File.OpenText(strFile);
string strGetLine;
while ((strGetLine = objStreamReader.ReadLine()) != null)
{
Response.Write(strGetLine);
}
How to download any file with Asp.Net
=================================
string FileName = Server.MapPath("style.css").ToString();
Response.Clear();
Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=Name.css;");
byte[] buffer = System.IO.File.ReadAllBytes(FileName);
System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);
mem.WriteTo(Response.OutputStream);
Response.End();
Render GridView to Html String
==========================
In many times I have faced a problem when you want to
render html string for GridView Control, but you
probably find error like...
"Control '' of type 'GridView' must be placed inside a form tag with runat=server."
In this case you have to use one method to avoid this error..
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
// specified ASP.NET server control at run time.
// No code required here.
}
and in the page directives just add this code marked in Bold Text..
Useful Javascript with Asp.Net
Open Popup Window in the Center of the screen.
=============================================
function OpenPop(ItemID)
{
var LeftPosition = (screen.width) ? (screen.width-505)/2 : 0;
var TopPosition = (screen.height) ? (screen.height-250)/2 : 0;
window.open('Pop_QuoteInfo.aspx?id='+ItemID,'MyTitle','height=250,width=505, top='+ TopPosition +', left='+LeftPosition+', scrollbars=yes, resizable=yes, status=no');
}
Javascript Trim() Function
=========================
function trim(inputString) {
// Removes leading and trailing spaces from the passed string. Also removes
// consecutive spaces and replaces it with one space. If something besides
// a string is passed in (null, custom object, etc.) then return the input.
if (typeof inputString != "string") { return inputString; }
var retValue = inputString;
var ch = retValue.substring(0, 1);
while (ch == " ") { // Check for spaces at the beginning of the string
retValue = retValue.substring(1, retValue.length);
ch = retValue.substring(0, 1);
}
ch = retValue.substring(retValue.length-1, retValue.length);
while (ch == " ") { // Check for spaces at the end of the string
retValue = retValue.substring(0, retValue.length-1);
ch = retValue.substring(retValue.length-1, retValue.length);
}
while (retValue.indexOf(" ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ")+1, retValue.length); // Again, there are two spaces in each of the strings
}
return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function
How to set Default Button in Asp.Net
===============================
Just, Simply add this code to your page_load() event in code file.
txtUserID.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnLogin.UniqueID + "').click();return false;}} else {return true}; ");
Enable / Disable Validator Control by Javascript
========================================
function EnableDisableControl()
{
var ctl1 = document.getElementById('RequiredValidator1');
// Disable
ValidatorEnable(ctl1, false);
// Enable
ValidatorEnable(ctl1, true);
}
Set/Get value from Popup page and Parent Page
========================================
Get Value in Popup page from Parent Page
---------------------------------------------------
// Write this Javascript in Popup Page
var ParentIDValue = window.opener.document.getElementById('').value;
alert(ParentIDValue);
Set Value in Parent Page from Popup Page
--------------------------------------------------
// Write this Javascript in Popup Page
window.opener.document.getElementById('').value = "Your Value From Popup Page..";
=============================================
function OpenPop(ItemID)
{
var LeftPosition = (screen.width) ? (screen.width-505)/2 : 0;
var TopPosition = (screen.height) ? (screen.height-250)/2 : 0;
window.open('Pop_QuoteInfo.aspx?id='+ItemID,'MyTitle','height=250,width=505, top='+ TopPosition +', left='+LeftPosition+', scrollbars=yes, resizable=yes, status=no');
}
Javascript Trim() Function
=========================
function trim(inputString) {
// Removes leading and trailing spaces from the passed string. Also removes
// consecutive spaces and replaces it with one space. If something besides
// a string is passed in (null, custom object, etc.) then return the input.
if (typeof inputString != "string") { return inputString; }
var retValue = inputString;
var ch = retValue.substring(0, 1);
while (ch == " ") { // Check for spaces at the beginning of the string
retValue = retValue.substring(1, retValue.length);
ch = retValue.substring(0, 1);
}
ch = retValue.substring(retValue.length-1, retValue.length);
while (ch == " ") { // Check for spaces at the end of the string
retValue = retValue.substring(0, retValue.length-1);
ch = retValue.substring(retValue.length-1, retValue.length);
}
while (retValue.indexOf(" ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ")+1, retValue.length); // Again, there are two spaces in each of the strings
}
return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function
How to set Default Button in Asp.Net
===============================
Just, Simply add this code to your page_load() event in code file.
txtUserID.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnLogin.UniqueID + "').click();return false;}} else {return true}; ");
Enable / Disable Validator Control by Javascript
========================================
function EnableDisableControl()
{
var ctl1 = document.getElementById('RequiredValidator1');
// Disable
ValidatorEnable(ctl1, false);
// Enable
ValidatorEnable(ctl1, true);
}
Set/Get value from Popup page and Parent Page
========================================
Get Value in Popup page from Parent Page
---------------------------------------------------
// Write this Javascript in Popup Page
var ParentIDValue = window.opener.document.getElementById('').value;
alert(ParentIDValue);
Set Value in Parent Page from Popup Page
--------------------------------------------------
// Write this Javascript in Popup Page
window.opener.document.getElementById('').value = "Your Value From Popup Page..";
Use Delegate and Events in Asp.Net
I'm explaining Delegates and Event with the use of UserControl and Form in the Asp.Net Webpage.
Steps for usercontrol
====================
1. First create one user control (Like ucTestDelegate)
2. Declare one Delegate (dont declare it in with in function but declare it in class)
3. Declare one event that uses this delegate (Declare it in class)
4. signature of event and Delegate function must match
// Declare one Delegate with its signature means with its return types and parameters.
public delegate void TestDelegateHandler(object sender, EventArgs e);
//Declare one Event that handle by our Delegate.
public event TestDelegateHandler TestDelegateFunction;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
this.lblMessage.Text = "Send Button Pressed";
TestDelegateFunction(sender, e);
}
Steps for Form
===============
1. Drag this usercontrol into page.
2. now Declare one function that has the same name and same Signature as the delegate have.
Example :
private void UcTestDelegate1_TestDelegateFunction(object sender, EventArgs e)
{
lblMessage.Text = " Page Label contains : " + "
" + "Test Delegate Function Calls";
}
3. Now in page load event of page Use the += operator to associate an event with an instance of a delegate that already exists.
protected void Page_Load(object sender, EventArgs e)
{
UcTestDelegate1.TestDelegateFunction +=new ucTestDelegate.TestDelegateHandler(UcTestDelegate1_TestDelegateFunction);
}
4. When you run Form And press send Button First the event of usercontrol calls and then of form. (To see how it calls debug both the events).
Steps for usercontrol
====================
1. First create one user control (Like ucTestDelegate)
2. Declare one Delegate (dont declare it in with in function but declare it in class)
3. Declare one event that uses this delegate (Declare it in class)
4. signature of event and Delegate function must match
// Declare one Delegate with its signature means with its return types and parameters.
public delegate void TestDelegateHandler(object sender, EventArgs e);
//Declare one Event that handle by our Delegate.
public event TestDelegateHandler TestDelegateFunction;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
this.lblMessage.Text = "Send Button Pressed";
TestDelegateFunction(sender, e);
}
Steps for Form
===============
1. Drag this usercontrol into page.
2. now Declare one function that has the same name and same Signature as the delegate have.
Example :
private void UcTestDelegate1_TestDelegateFunction(object sender, EventArgs e)
{
lblMessage.Text = " Page Label contains : " + "
" + "Test Delegate Function Calls";
}
3. Now in page load event of page Use the += operator to associate an event with an instance of a delegate that already exists.
protected void Page_Load(object sender, EventArgs e)
{
UcTestDelegate1.TestDelegateFunction +=new ucTestDelegate.TestDelegateHandler(UcTestDelegate1_TestDelegateFunction);
}
4. When you run Form And press send Button First the event of usercontrol calls and then of form. (To see how it calls debug both the events).
Encrypt - Decrypt with DES and MD5 Algorithm
Encrypt - Decrypt with DES Algorithm
================================
// Use this Namespace
using System.Security.Cryptography;
// Encrypt Function
public static string Encryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateEncryptor(Key_64, Iv_64), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(value);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}
return string.Empty;
}
// Decrypt Function
public static string Descryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
Byte[] buf = Convert.FromBase64String(value);
MemoryStream ms = new MemoryStream(buf);
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateDecryptor(Key_64, Iv_64), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
return string.Empty;
}
Encrypt with MD5 Algorithm
========================
// Encrypt Function
public static string EncryptWithMD5(string ClearString)
{
System.Text.UnicodeEncoding objUE = new System.Text.UnicodeEncoding();
byte[] bytClearString = objUE.GetBytes(ClearString);
MD5CryptoServiceProvider objProv = new MD5CryptoServiceProvider();
byte[] hash = objProv.ComputeHash(bytClearString);
return Convert.ToBase64String(hash);
}
================================
// Use this Namespace
using System.Security.Cryptography;
// Encrypt Function
public static string Encryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateEncryptor(Key_64, Iv_64), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(value);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}
return string.Empty;
}
// Decrypt Function
public static string Descryption(string value)
{
if (value != "")
{
DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
Byte[] buf = Convert.FromBase64String(value);
MemoryStream ms = new MemoryStream(buf);
CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateDecryptor(Key_64, Iv_64), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
return string.Empty;
}
Encrypt with MD5 Algorithm
========================
// Encrypt Function
public static string EncryptWithMD5(string ClearString)
{
System.Text.UnicodeEncoding objUE = new System.Text.UnicodeEncoding();
byte[] bytClearString = objUE.GetBytes(ClearString);
MD5CryptoServiceProvider objProv = new MD5CryptoServiceProvider();
byte[] hash = objProv.ComputeHash(bytClearString);
return Convert.ToBase64String(hash);
}
Normal string Encrypt and Decrypt
Encrypt and Decrypt string
======================
// Encrypt Method
private string EncryptString(string strSource)
{
Byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strSource);
string encryptedString = Convert.ToBase64String(b);
return encryptedString;
}
// Decrypt Method
private string DecryptString(string strSource)
{
Byte[] b = Convert.FromBase64String(strSource);
string decryptedString = System.Text.ASCIIEncoding.ASCII.GetString(b);
return decryptedString;
}
======================
// Encrypt Method
private string EncryptString(string strSource)
{
Byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strSource);
string encryptedString = Convert.ToBase64String(b);
return encryptedString;
}
// Decrypt Method
private string DecryptString(string strSource)
{
Byte[] b = Convert.FromBase64String(strSource);
string decryptedString = System.Text.ASCIIEncoding.ASCII.GetString(b);
return decryptedString;
}
SQL Server function for Count the Occurrence of Character in the string
SQL Server function for Count the Occurrence of Character in the string
============================================================
-- Author : Milind Kansagara
-- Date : 30 July, 2007
-- Desc : Count the Occurrence of Character in the string
-- Usage : select dbo.GetOccurrence('Abhishek Joshi','a')
CREATE FUNCTION [dbo].[GetOccurrence] ( @pInput VARCHAR(1000), @pSearchChar CHAR(1) )
RETURNS INT
BEGIN
DECLARE @vInputLength INT
DECLARE @vIndex INT
DECLARE @vCount INT
SET @vCount = 0
SET @vIndex = 1
SET @vInputLength = LEN(@pInput)
WHILE @vIndex <= @vInputLength
BEGIN
IF SUBSTRING(@pInput, @vIndex, 1) = @pSearchChar
SET @vCount = @vCount + 1
SET @vIndex = @vIndex + 1
END
RETURN @vCount
END
============================================================
-- Author : Milind Kansagara
-- Date : 30 July, 2007
-- Desc : Count the Occurrence of Character in the string
-- Usage : select dbo.GetOccurrence('Abhishek Joshi','a')
CREATE FUNCTION [dbo].[GetOccurrence] ( @pInput VARCHAR(1000), @pSearchChar CHAR(1) )
RETURNS INT
BEGIN
DECLARE @vInputLength INT
DECLARE @vIndex INT
DECLARE @vCount INT
SET @vCount = 0
SET @vIndex = 1
SET @vInputLength = LEN(@pInput)
WHILE @vIndex <= @vInputLength
BEGIN
IF SUBSTRING(@pInput, @vIndex, 1) = @pSearchChar
SET @vCount = @vCount + 1
SET @vIndex = @vIndex + 1
END
RETURN @vCount
END
Subscribe to:
Posts (Atom)