开发者

how to split a string

i have a string like 123Prefix1pics.zip

开发者_JS百科

i want to split it into 123 Prefix1 pics.zip and store them in different variables i m trying to do it in c#,.net jst litle bit confused on how to use split method


splitArray = Regex.Split(subjectString, @"(?<=\p{N})(?=\p{L})");

will work in C# to split in positions between a number (\p{N}) and a letter (\p{L}).

If you also want to split between a letter and a number, use

splitArray = Regex.Split(subjectString, @"(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})");

however, that splits your example too much.


You only want to split that one string? Too easy!

string filename = "123Prefix1pics.zip"
string part1 = "123"
string part2 = "Prefix1"
string part3 = "pics.zip"

Ok this is a joke, but it gives the right answer. Unless you generalise your splitting rule, or provide further examples, we can only guess.

You may be asking to make a string break after a numeral, but again I'm only guessing.


You can start with:

string filename = "123Prefix1pics.zip"
string part1 = filename.Substring(0, 3);
string part2 = filename.Substring(3, 7);
string part3 = filename.Substring(10, 4);

You can also note String.Split() needs a separator argument, like an ; or ,. As you don't have any separator, you can try two approaches:

  • Make sure all your filenames have same format; this way, you can to use Substring() to break your strings
  • You can identify a more general pattern, as "numbers, 7 characters plus 4 more characters" and to use a regular expression. This is a more advanced solution and can lead to maintenance problems;

I recommend you to stick with first option.


You can split it like this:

  • your ip in a string variable like this:
  • create a char vector
  • then a string vector

Code:

string theIP="this is string"; 
char[] separator={' '}; //you can put multiple separators
string[] result = theIP.Split(separator,StringSplitOptions.None);

this means result[0] is "this", result[1] is "is", and so on.

You can find a good tutorial about string splitting here:

http://goldwin-advertising.ro/index.php?option=com_content&view=article&id=10:splitstring&catid=3:howto&Itemid=5

Good luck!


Look like you want to split by fixed size.

So use yourString.Substring(0, 3);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜