C# String Functions and Manipulation

0 comments

C# String Functions and Manipulation

Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use theTrim(). 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);
}
String s="Andrew was here"
Example
Value
Comment
s+" once"
"Andrew was here once"
The strings are concatenated using +
s.Equals("another")
false
Also s == "another" Tests for equality
s.IndexOf("was")
6
Returns -1 if the substring is not there.
s.Length
14
The number of characters
s.Split(" ")
["Andrew","was","here"]
Returns an array of String.
s.Substring(2,7)
"drew wa"
Characters from position 2. 7 characters are taken
s.ToUpper()
"ANDREW WAS HERE"
Also .toLowerCase()


ALL OPERATIONS(Manipulations )

using System;
using System.Text;

namespace ex5
{
    class Program
    {
        static void Main(string[] args)
        {
            // Concat
            string a="David ";
            int b = 0;
            a= string.Concat(a,4,5.6,b);
            Console.WriteLine("a= {0}",a);
           
            // Contains
            if (a.Contains("45.6"))
              Console.WriteLine("{0} contains 45.6",a);

            // IndexOf
            int pos = a.IndexOf(".6");
            Console.WriteLine("position of .6 is {0}", pos);

            //Split and Join
            string commatext = "alpha,bravo,charlie";
            string[] words = commatext.Split(',');
            string dashed = string.Join("---", words);
            Console.WriteLine("Dashed join is {0}", dashed);

            string spacedout = commatext.PadLeft(commatext.Length + 10); // insert ten spaces to the left
            commatext = spacedout.PadRight(spacedout.Length + 5, '*'); // and ***** to the right
            Console.WriteLine("commatext is {0}", commatext);

            string s1 = "".PadRight(60) + '*';
            string s2 = String.Empty.PadRight(60) + '*';
            if (s1 == s2)
                Console.WriteLine("They're the same!");
            else
                Console.WriteLine("They're not the same!");
            Console.WriteLine("s1 is {0}", s1);

            if (s1.StartsWith("   "))
                Console.WriteLine("S1 starts with spaces");
            if (s1.EndsWith("  *"))
                Console.WriteLine("S1 ends with spaces and a *");
            Console.ReadKey();


        }
    }
}

Advanced Csharp String Functions

Capitalize
This C# function takes the first letter of a string an capitalizes it:
word -> Word
this is a sentence -> This is a sentence
IsCapitalized
This C# function checks to see if the first letter of a string is capitalized:
Word -> True
word -> False
IsLowerCase
Checks to see that an entire string is in lower cases
word -> True
Word -> False
IsUpperCase
Checks to see that an entire string is in upper cases
Word -> False
WORD -> True
SwapCases
This C# function swaps the cases of a string
word -> WORD
Word -> wORD
AlternateCases
Takes the first character's casing an alternates the casing of the rest of the string
Hi -> Hi
helloworld -> hElLoWoRlD
AlternateCases    
This C# string function works exactly the same except the user specifies on which case the string will start (Upper case or Lower case)
IsAlternateCases
Checks to see whether a string has alternating cases
CountTotal
Counts the total number of occurances of a string within another string
hello, l -> 2
hello, el -> 1
RemoveVowels
This C# string function removes the vowels in a string
hello -> hll
KeepVowels
This C# string function removes everything but the vowels in a string
hello -> eo
HasVowels
Checks to see if there is any vowel psent in a string
IsSpaces
Quickly and effortlessly checks to see if a string is nothing but spaces
IsRepeatedChar
Quickly and effortlessly checks to see if a string is nothing but the same letter repeated
aaaaaaaaaa -> True
aaaaaaaaad -> False
IsNumeric
Processes a string to see if it contains only numbers
HasNumbers
Checks a string to see if it contains any numbers.
IsAlphaNumberic
This C# function evaluates whether a string contains only numbers and letters (no symbols).
isLetters
Checks for a string to contain nothing but letters, no numbers or symbols.
GetInitials
Converts a string, like a name, into its initials
Bob Landon -> B.L.
GetTitle
Capitalizes the first letter of every word in a string
the good story -> The Good Story
GetNameCasing
Similar to the GetTitle function, capitalizes the first letter of every word, but has some additional rules for names
mcdonald -> McDonald
macdonald -> MacDonald
Credits to ShutlOrbit (
http://www.thirdstagesoftware.com) from CodeProject
IsTitle
This C# string function checks if the first letter of every word is capitalized
The Big Story -> True
The big story -> False
IsEmailAddress
Verifies that an email address is written in the correct format. Useful for checking email addressed entered in a web application.
IndexOfAll
This very useful C# function returns all the indicies of a string in another string. As opposed to IndexOf which only returns the first index.
ArrayToString
This C# string function is a must for all developers. Quickly turns any array into a single string that can be displayed to survey an array's data. Check out a more complete array to string function right here on Visual C# Kicks.
PasswordStrength
Evaluate the effectiveness of a string as a password. Original idea credits go to D. Rijmenants. (If there are any copyright issues please contact us).
CharRight
Basically a Substring function that works backwards. Programmers from older languages will appciate this missing C# function.
CharMid
Another function that is missing from the original C# Net string processing list. Works like Substring but starts from a specified position.
InsertSeparator
Inserts a separator after each letter in a string, excluding the last letter
hello, - -> h-e-l-l-o
InsertSeparatorEvery
Inserts a separator after a specified number of letters, excluding the last letter
SubstringEnd
This C# function works exactly like the built-in Substring. The only difference is it takes in a Start and End parameter instead of the default Start and Length. (Basically the Java version of Substring)
Reverse
Reverses a string without the need for a recursive function.
SplitQuotes
This C# function works like the built-in Split function. The only difference is it will respect parts of a string surrounded by quotes. For example the string This is a "very long" string would get split into: 
This
is
a
very long
string

Careful however, the function does not work with nested quotes.

 

string functions available in SQL Server 2005.
Function
Parameters
Description
Example and  Output
ASCII
(character_expression)
Returns the ASCII code value of the leftmost character of a character expression.
Select Ascii(‘ABC’)   O/P : 65
CHAR
( integer_expression )
Converts anint ASCII code to a character.
Select Char(65)         O/P:A
CHARINDEX
( expression1,expression2 [ ,start_location )
Searchesexpression2forexpression1and returns its startingposition if found. The search starts atstart_location.
SELECT CHARINDEX ( ‘TEST’,'Das ist ein Test’)
DIFFERENCE
(character_expression ,character_expression)
Returns an integer value that indicates the difference between the SOUNDEXvalues of two character expressions.
SELECT DIFFERENCE(‘Green’,'Greene’);
LEFT
(character_expression ,integer_expression )
Returns the left part of a character string with the specified number of characters.
SELECT LEFT(‘abcdefg’,2)    O/P: ab
LEN
( string_expression )
Returns the number of characters of the specified string expression, excluding trailing blanks.
Select Len(‘abcd’) O/P: 4
LOWER
(character_expression)
Returns a character expression after converting uppercase character data to lowercase.
Select Lower(‘ABCD’)     O/P: abcd
LTRIM
(character_expression)
removes leading blanks.
Select Ltrim(‘      6blanks’)
NCHAR
( integer_expression )
Returns the Unicode character with the specified integer code,
Select Nchar(75)   O/P: K
PATINDEX
( %pattern% ,expression )
Returns the startingposition of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found
SELECT PATINDEX ( ‘%ein%’, ‘Das ist ein Test’ )
QUOTENAME
( character_string [ ,'quote_character' ] )
Returns a Unicode string with the delimiters added to make the input string a validMicrosoft SQL Serverdelimited identifier.
SELECT QUOTENAME(‘abc[]def’)   O/P: [abc[]]def]
REPLACE
string_expression1 ,string_expression2 ,string_expression3 )
Replaces all occurrences of a specified string value with another string value.
SELECT REPLACE(‘abcdefghicde’,'cde’,'xxx’);   O/P: abxxxfghixxx
REPLICATE
( string_expression,integer_expression )
Repeats a string value a specified number of times.
SELECT  REPLICATE(‘A’, 4)
REVERSE
(character_expression)
reverse of a character expression.
Select Reverse(‘ABC’) O/P: CBA
RIGHT
(character_expression ,integer_expression )
Returns the right part of a character string with the specified number of characters.
Select Right(‘ABCD’,2) O/P: CD
RTRIM
(character_expression)
truncates all trailing blanks
Select rtrim(’6trailingBlanks      ‘)
SOUNDEX
(character_expression)
Returns a four-character (SOUNDEX) code
Select Soundex(‘Smith’)   O/P: S580
SPACE
( integer_expression )
Returns a string of repeated spaces.
Select space(7)
STR
( float_expression ,length , decimal ] ] )
Returns character data converted from numeric data.
SELECT STR(123.45, 6, 1);  O/P: 123.5
STUFF
(character_expression ,start length,character_expression)
The STUFFfunctioninserts a string into another string. It deletes a specified length of characters in the first string at the start positionand then inserts the second string into the first string at the startposition.
SELECT STUFF(‘abcdef’, 2, 3, ‘ijklmn’);    O/P: aijklmnef
SUBSTRING
value_expression,start_expression ,length_expression )
Returns part of a character,binary, text, or image expression
SELECT SUBSTRING(‘abcdef’, 2, 3);   O/P: bcd
UNICODE
(Ncharacter_expression)
Returns the integer value, as defined by the Unicode standard, for the first character of the input expression.
Select unicode(‘kite’)  O/P:107
UPPER
(character_expression)
 



 

Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com