假设我有这个字符串:
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";
是否可以?
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);
您可以执行以下操作:
string [] stringparts mystring.spilt('|');
stringsparts
可用于打印您想要的任何内容。
使用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);
您可以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
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);
这是 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;
实现它的一种简短方法:-
myString = myString.Substring(myString.LastIndexOf("|") + 1);