[英]How to use String.Replace
快速提问:
我有这个字符串m_Author, m_Editor
但是我在字符串中有一些奇怪的ID东西,因此,如果我执行WriteLine
,它将看起来像:
'16; #Luca Hostettler'
我知道我可以执行以下操作:
string author = m_Author.Replace("16;#", "");
string editor = m_Editor.Replace("16;#", "");
之后,我将有一个名字,但是我认为将来我还会有其他人和其他ID。
所以问题是:我可以告诉String.Replace("#AndEverythingBeforeThat", "")
所以我也可以
'14; #Luca Hostettler'
'15; #Hans Meier'
并得到输出:Luca Hostettler,Hans Meier,而无需手动将代码更改为m_Editor.Replace("14;#", ""), m_Editor.Replace("15;#", "")
...?
听起来您想要一个正则表达式为“至少一个数字,然后是分号和哈希”,并带有一个“仅在字符串开头”的锚点:
string author = Regex.Replace(m_Author, @"^\d+;#", "");
或使其更可重用:
private static readonly Regex IdentifierMatcher = new Regex(@"^\d+;#");
...
string author = IdentifierMatcher.Replace(m_Author, "");
string editor = IdentifierMatcher.Repalce(m_Editor, "");
请注意,在以下情况下,可能会有不同的适当解决方案:
您可以使用正则表达式或(我更喜欢) IndexOf
+ Substring
:
int indexOfHash = m_Author.IndexOf("#");
if(indexOfHash >= 0)
{
string author = m_Author.Substring(indexOfHash + 1);
}
要不就,
var author = m_Author.Split('#').Last();
您可以使用string.Split()函数使用#拆分字符串,这将为您提供两个字符串,首先是#之前的所有内容,然后是#之后的所有内容
使用String.Format
int number=5;
string userId = String.Format("{0};#",number)
string author = m_Author.Replace(userId, "");
如果您只想过滤掉所有不是字母或空格的内容,请尝试:
var originalName = "#123;Firstname Lastname";
var filteredName = new string(originalName
.Where(c => Char.IsLetter(c) ||
Char.IsWhiteSpace(c))
.ToArray());
该示例将产生Firstname Lastname
List<char> originalName = "15;#Hans Meier".ToList();
string newString = string.Concat(originalName.Where(x => originalName.IndexOf(x) > originalName.IndexOf('#')).ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.