0

假设我有这个字符串:

String myString = "violet are blue|roses are red|this is a terrible poet";

每当找到字符'|'时,我想修剪字符串。因此,当执行代码时, myString 将是:

myString = "roses are red|this is a terrible poet";

最后

myString = "this is a terrible poet";

是否可以?

4

7 回答 7

3
private string trimString(string s)
{
   int index = s.IndexOf("|");
   return s.Substring(index+1); //returns string from this index to the end of string
}

用法

String myString = "violet are blue|roses are red|this is a terrible poet";

myString = trimString(myString);
于 2012-12-15T09:41:32.640 回答
0

您可以执行以下操作:

 string [] stringparts mystring.spilt('|');

stringsparts可用于打印您想要的任何内容。

于 2012-12-15T09:36:29.330 回答
0

使用String.Split()方法;

//Single Line Solution
string newString1 = myString.Split('|').Last();


//Another way
string[] arr = myString.Split('|');   //Split the string by | into an array
string newString2 = arr[arr.Length-1]; //Get the last element of the splited array



Console.WriteLine(newString1);
于 2012-12-15T09:37:20.990 回答
0

您可以Substring为此使用方法,也许您可​​能希望将其用作扩展方法。代码包括修剪到第一个(左)和修剪到最后一个(右)|

public static class StringExtensions
{
    public static string TrimToFirst(this string s)
    {
        int index = s.IndexOf('|');
        if(index >= 0)
        {
            s = s.Substring(index + 1);
        }
        return s;
    }

    public static string TrimToLast(this string s)
    {
        int index = s.LastIndexOf('|');
        if(index >= 0)
        {
            s = s.Substring(index + 1);
        }
        return s;
    }
}

// usage
string myString = "violet are blue|roses are red|this is a terrible poet";
Console.WriteLine(myString.TrimToLast());
// outpus: this is a terrible poet
于 2012-12-15T09:39:39.347 回答
0
string myString = "violet are blue|roses are red|this is a terrible poet";
var elements = myString.Split(new char[] { '|' }).Skip(1);

StringBuilder sb = new StringBuilder();
foreach (var element in elements)
{
    sb.Append(element);
    sb.Append("|");
}

string result = sb.Remove(sb.Length - 1, 1).ToString();

Console.WriteLine(result);
于 2012-12-15T09:41:34.040 回答
0

这是 100,000000 种方法之一

string myString = "violet are blue|roses are red|this is a terrible poet";
string result = myString.Contains('|') ? myString.Substring(myString.IndexOf('|')).TrimStart('|') : myString;
于 2012-12-15T09:50:25.160 回答
0

实现它的一种简短方法:-

myString = myString.Substring(myString.LastIndexOf("|") + 1);
于 2012-12-24T19:05:38.767 回答