在String上找到特定字符时修剪字符串,是否可能?

时间:2012-12-15 09:32:24

标签: c# string

让我说我有这个字符串:

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

我想在发现char'|'时修剪String。因此,当代码执行时,myString将是:

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

最后

myString = "this is a terrible poet";

有可能吗?

7 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您可以执行以下操作:

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

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

答案 2 :(得分: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);

答案 3 :(得分: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

答案 4 :(得分: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);

答案 5 :(得分: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;

答案 6 :(得分:0)

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

myString = myString.Substring(myString.LastIndexOf("|") + 1);