开发者

C#: How can I cut a String based on a Value?

I have this string:

value1*value2*value3*value4

How would cut the Strin开发者_StackOverflow中文版g in multiple Strings?

string1 = value1;
string2 = value2;
etc...

My way (and probably not a very good way): I take an array with all the indexes of the "*" character and after that, I call the subString method to get what I need.


string valueString = "value1*value2*value3*value4";
var strings = valueString.Split('*');
string string1 = strings[0];
string string2 = strings[1];
...

More info here.


Try this

string string1 = "value1*value2*value3*value4";
var myStrings = string1.Split('*');


string s = "value1*value2*value3*value4";
string[] array = s.Split('*');


simply :

 string[] parts = myString.Split("*");

parts will be an array of string (string[])


you can just use the Split() method of the String-Object like so:

String temp = "value1*value2*value3*value4";
var result = temp.Split(new char[] {'*'});

The result variable is a string[] with the four values.


If you want to shine in society, you can also use dynamic code :

using System;
using System.Dynamic;

namespace ConsoleApplication1
{
    class DynamicParts : System.Dynamic.DynamicObject
    {
        private string[] m_Values;

        public DynamicParts(string values)
        {
            this.m_Values = values.Split('*');
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var index = Convert.ToInt32(binder.Name.Replace("Value", ""));
            result = m_Values[index - 1];
            return true;
        }


        public static void Main()
        {

            dynamic d = new DynamicParts("value1*value2*value3*value4");

            Console.WriteLine(d.Value1);
            Console.WriteLine(d.Value2);
            Console.WriteLine(d.Value3);
            Console.WriteLine(d.Value4);

            Console.ReadLine();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜