This article provides Tips and Tricks for using string in C#.Net.
1. Passing Double Quotes (“) in C# String
Most of the applications are required to pass a string with double quotes to the sqlparameter to execute a stored procedure.
1
2
|
string str = @“Doube Quote “” in string”;
MessageBox.Show(str);
|
Output
2. C# string reverse
Unfortunately Reverse() function is not available in C# string class, so we can use following approach to reverse string:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
private void button1_Click(object sender, EventArgs e)
{
string str = “C#.Net string reverse”;
string strReverse = ReverseStr(str);
MessageBox.Show(strReverse);
}
public string ReverseStr(string str)
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
|
Output
3. Search string in c# RichTextBox
The Find method of the RichTextBox control searches for string given in the string parameter. If string found it returns the first character position of the search string in the RichTextBox. If the text is not found, the Find method returns -1. By specifying the same value for the start position and the end position, the Find() finds the entire string, starting from the zero position.
1
2
3
4
5
6
7
8
9
10
11
12
|
private void btnSearch_Click(object sender, EventArgs e)
{
string word = txtSearch.Text;
int s_start = richTextBox1.SelectionStart, startIndex = 0, index;
while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != –1)
{
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionBackColor = Color.Yellow;
startIndex = index + word.Length;
}
}
|
Output
4. c# string split
This C# tip shows the string.Split method. It uses a character to split given string.
1
2
3
4
5
6
7
8
9
|
string str = “C# String Tips and Tricks”;
// pass character in single quote,in this example string will split on space
string[] arr = str.Split(‘ ‘);
for (int i = 0; i < arr.Length; i++)
{
listBox1.Items.Add(arr[i]);
}
|
Output
Source techzoo.org