String In Csharp

 

Saturday, May 30, 2009

Reverse String in C#

public string strReverse(string s)
{
int j=0;
char[] c=new char[s.Length];
for(int i=s.Length-1;i>=0;i--) c[j++]=s[i];
return new string(c);
}

Extract Numbers From String

private string ExtractNumbers(string Expression)
{
string result = null;
char Letter;

for (int i = 0; i < Expression.Length; i++)
{
Letter = Convert.ToChar(Expression.Substring(i, 1));

if (Char.IsNumber(Letter))
{
result += Letter.ToString();
}
}

// MessageBox.Show(result);
return result;
}

Locate string on webpage

// Locate string on webpage

private bool SearchPage(string URL, string StrToLocate)
{
StreamReader SR;
WebResponse Resp ;
WebRequest MyWebRequest;
string PageStr;

MyWebRequest = WebRequest.Create(URL) ;
MyWebRequest.Timeout = 10000 ;
try
{
Resp = MyWebRequest.GetResponse() ;
SR = new StreamReader(Resp.GetResponseStream()) ;
PageStr = SR.ReadToEnd() ;
SR.Close() ;

PageStr = PageStr.ToUpper();
if ( PageStr.IndexOf(StrToLocate.ToUpper(), 0, PageStr.Length) != -1 )
return true;
else
return false;
}

catch ( WebException wex )
{
if (wex.Status == WebExceptionStatus.Timeout)
Response.Write("The request has timed out!") ;

else
Response.Write("There was some exception: " + wex.Message) ;

return false;
}

}

Detect if string is numeric

// Detect if a string is numeric

public static bool IsNumeric(string text)
{
return Regex.IsMatch(text,"^\\d+$");
}

Convert ArrayList to string[]

/*
Convert ArrayList to string[]
-
Given an ArrayList of strings, here's how to convert it to a string array:
*/

string[] srtArray = arrList.ToArray(Type.GetType("System.String")) as string[];

Numeric textbox (accepts only numbers and shows a warning popup when invalid)

// Numeric textbox (accepts only numbers and shows a
// warning popup when invalid)

public class NumericTextbox : TextBox
{
protected override CreateParams CreateParams {
get
{
CreateParams cp = base.CreateParams;
cp.Style |= 0x2000; // ES_NUMBER
return cp;
}
}
}

Protect string content by marshalling

// Protect string content by marshalling

IntPtr bstr = Marshal.SecureStringToBSTR(password);

try
{
// ...
// use the bstr
// ...
}
finally
{
Marshal.ZeroFreeBSTR(bstr);
}

All Menu