Several methods of segmenting strings in C #

zhaozj2021-02-16  83

Recently, many posts in the forum have often seen how to use split to split strings. I will do some simple summary for splits, I hope to help everyone. Here are several ways:

The first method: Open VS.NET to create a new console project. Then enter the following programs under the main () method.

String s = "abcdeabcdeabcde";

String [] Sarray = S.Split ('c');

FOREACH (String I in Sarray)

Console.writeline (i.tostring ());

Output the following result: ab

DEAB

DEAB

de

We see the result is divided in a specified character. If we want to use multiple characters to split how C, D, E do? Ok, we use another constructor:

Change to string s = "abcdeabcdeabcde

String [] Sarray1 = S.Split (New Char [3] {'C', 'D', 'E'});

FOREACH (String I in Sarray1)

Console.writeline (i.tostring ());

You can output the following results: ab

AB

AB

In addition to the above two methods, the third method is to use a regular expression. Create a new console project. Then add USING SYSTEM.TEXT.REGULAREXPRESSITIONS.

Main (): Changed to

System.Text.RegularExpressions

String content = "agcsmallmAcsmallgggsmallytx";

String [] resultstring = regex.split (content, "small", regexoptions.ignorecase)

FOREACH (String I in Resultstring)

Console.writeline (i.tostring ());

Output the following results: AGC

Mac

GGG

YTX

What is the benefit of using regular expressions? Don't worry, we will see its uniqueness.

The fourth method is described below. such as

String str1 = "I ***** is the ***** one ***** ***** teaching ***** teacher";

If I want to be displayed: I am a teacher, how do you work? We can use the following code:

String str1 = "I ***** is the ***** one ***** ***** teach ***** teacher;

String [] str2;

Str1 = str1.replace ("*****", "*");

Str2 = str1.split ('*');

FOREACH (String I in str2)

Console.writeline (i.tostring ());

This can also get the correct result. But for example

String str1 = "I ** is ***** one ***** ***** teaching ***** teacher";

I hope that the result is: I am a teacher.

If I use the fourth method above, I will generate the following error: I am a teacher.

There is space in the middle, so the output is not the result I hope, how to solve it? This also returns to the regular expression (here you can see its powerful power), then the fifth method can be used at this time:

String str1 = "I ** is ***** one ***** ***** teaching ***** teacher";

String [] str2 = system.text.RegularExpressions.Regex.Split (str1, @ "[*] "); foreach (String I in str2)

Console.writeline (i.tostring ());

Here is the "[*] " clever completed our goals.

The above introduction to several ways to split strings in C #, if you have a better way, please communicate with me :)

转载请注明原文地址:https://www.9cbs.com/read-14597.html

New Post(0)