开发者

how to split string?

<span style="cursor: pointer;">$$</span>

how can i get <span style="cursor: p开发者_JAVA百科ointer;"> and </span> from this string. Everything around $$.

No need to be regex.


Well, you could just use:

string[] bits = input.Split(new string[]{"$$"}, StringSplitOptions.None);

Note that unlike the overloads taking char separators, you have to provide the StringSplitOptions, and you have to manually create the array. (Of course if you're going to do this repeatedly you would probably want to reuse the array.) You can also optionally specify the maximum number of tokens to split the input into. See the string.Split overload list for more information.

Short but complete program:

using System;

public static class Test
{
    public static void Main()
    {
        string input = "<span style=\"cursor: pointer;\">$$</span>";
        string[] bits = input.Split(new string[]{"$$"},
                                    StringSplitOptions.None);

        foreach (string bit in bits)
        {
            Console.WriteLine(bit);
        }
    }    
}

Of course if you know there are only going to be two parts, another option is to use IndexOf:

int separatorIndex = input.IndexOf("$$");
if (separatorIndex == -1)
{
    throw new ArgumentException("input", "Oh noes, couldn't find $$");
}
string firstBit = input.Substring(0, separatorIndex);
string secondBit = input.Substring(separatorIndex + 2);


Or you can use IndexOf to find the "$$" and then use a Substring method to get either side.

Example

        string s = "<span style=\"cursor: pointer;\">$$</span>";
        string findValue = "$$";

        int index = s.IndexOf(findValue);

        string left = s.Substring(0, index);
        string right = s.Substring(index + findValue.Length);


You can use a SubString() method:

string _str = "<span style=\"cursor: pointer;\">$$</span>";
int index = _str.IndexOf("$$");
string _a = _str.Substring(0, index);
string _b = _str.Substring(index + 2, (_str.Length - index - 2));

Mitja

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜