using …

Pure C#

04 Ara_Aralık_kısaltma 2008 için Arşiv

String Manipulation in C#

Yazan: esersahin 04/12/2008

http://www.developerfusion.com/code/4398/string-manipulation-in-c/

Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). 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 dilemeter

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]));

Yazı kategorisi: split | » yorum bırak;

How To: Joining and Splitting Strings

Yazan: esersahin 04/12/2008

http://www.csharp-station.com/HowTo/StringJoinSplit.aspx

Introduction

When developing programs that interoperate with external systems, it’s often necessary to process data in a common format.  For example, a program may wish to process data from an Excel spreadsheet.  Excel has the capability to export a worksheet in Comma Separated Value (CSV) format.  Using the string Split() method allows you to extract the values from in between the commas.  Similarly, the string Join() method will take individual values from an array and combine them with a separator, such as a comma.  The listing below shows how to use the string Split() and Join() methods:

Listing 1: Joining and Splitting Strings: StringJoinSplit.cs

using System;

namespace csharp_station.howto
{
    class StringJoinSplit
    {
        static void Main(string[] args)
        {
            // comma delimited string
            string commaDelimited = “Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec”;

            Console.WriteLine(“Original Comma Delimited String: \n{0}\n”, commaDelimited);

            // separate individual items between commas
            string[] year = commaDelimited.Split(new char[] {‘,’});

            Console.WriteLine(“Each individual item: “);

            foreach
(string month in year)
            {
                Console.Write(“{0} “, month);
            }
            Console.WriteLine(“\n”);

            // combine array elements with a new separator
            string colonDelimeted = String.Join(“:”, year);

            Console.WriteLine(“New Colon Delimited String: \n{0}\n”, colonDelimeted);

            string
[] quarter = commaDelimited.Split(new Char[] {‘,’}, 3);

            Console.WriteLine(“The First Three Items: “);

            foreach
(string month in quarter)
            {
                Console.Write(“{0} “, month);
            }
            Console.WriteLine(“\n”);

            string
thirdQuarter = String.Join(“/”, year, 6, 3);

            Console.WriteLine(“The Third Quarter: \n{0}\n”, thirdQuarter);
        }
    }
}

And here’s the output:

Original Comma Delimited String:
Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

Each individual item:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

New Colon Delimited String:
Jan:Feb:Mar:Apr:May:Jun:Jul:Aug:Sep:Oct:Nov:Dec

The First Three Items:
Jan Feb Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

The Third Quarter:
Jul/Aug/Sep

In the listing above, there is a CSV string named commaDelimited, which holds the twelve months of the year, separated by commas.  It splits this string, joins it into another string, performs a three element split, and finally does a selective join of the 6th through 8th elements of a zero-based array.

The simplest syntax of the Split() method accepts a character array as it’s only parameter, listing the characters to use in determining where splitting of the string should occur.  It returns an array of strings, with each element of the array corresponding to the value between the specified delimiter(s).  The line below is from the first split operation in the listing:

            string[] year = commaDelimited.Split(new char[] {‘,’});

In a similar manner, elements of an array may be combined into a delimited string by using the Join() method.  The simplest overload of the Join() method accepts two parameters: a string, which separates each array element, and the array of elements to be combined.  The Join() method is static, requiring the String type identifier, rather than a string instance, to implement the command.  The following line from the listing creates a string with all year elements in sequence, separated by colons:

            string colonDelimeted = String.Join(“:”, year);

Overloads

Those were the simple implementations of these methods, and probably the most likely to be used.  Now lets take a peek at a couple of their overloads to see how to implement more specialized behavior.

The Split() method has an overload with a second parameter, specifying the number of separations to implement.  The next line will separate the commaDelimited string into three array elements:

            string[] quarter = commaDelimited.Split(new Char[] {‘,’}, 3);

At first thought, one may think that the three array elements could be Jan, Feb, and Mar, but this is not so.  The first array element is Jan, the second is Feb, and the last is the rest of the string.  To see for yourself, here’s the output string with each array element separated by a space:

Jan Feb Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

The Join() method has an overload that allows you to extract a subset of an array.  The first two parameters are the same as previously described, and the third and fourth parameters specify the position in the array to begin reading and the number of elements to read, respectively.  The following line from the listing creates a string with a forward slash between the sixth through eighth elements of  the year array:

            string thirdQuarter = String.Join(“/”, year, 6, 3);

Summary

The string Split() and Join() methods provide functionality to work with delimited strings.  The Split() method allows you to gather a delimited set of values from a string into an array and the Join() method lets you create a delimited string from an array.  This supports both custom data formats as well as information interchange with other programs.

Yazı kategorisi: split | » yorum bırak;

String.Split Method (Char[])

Yazan: esersahin 04/12/2008

http://msdn.microsoft.com/en-us/library/b873y76a(VS.80).aspx

using System;

public class SplitTest {
    public static void Main() {

        string words = “this is a list of words, with: a bit of punctuation.”;

        string [] split = words.Split(new Char [] {‘ ‘, ‘,’, ‘.’, ‘:’});

        foreach (string s in split) {

            if (s.Trim() != “”)
                Console.WriteLine(s);
        }
    }
}

See Also

Yazı kategorisi: split | » yorum bırak;