Quick question:
I have this String m_Author, m_Editor
But I have some weird ID stuff within the string so if I do a WriteLine
it will look like:
'16;#Luca Hostettler'
I know I can do the following:
string author = m_Author.Replace("16;#", "");
string editor = m_Editor.Replace("16;#", "");
And after that I will just have the name, But I think in future I will have other people and other ID's.
So the question: Can I tell the String.Replace("#AndEverythingBeforeThat", "")
So i could also have
'14;#Luca Hostettler'
'15;#Hans Meier'
And would get the Output: Luca Hostettler, Hans Meier, without changing the code manually to m_Editor.Replace("14;#", ""), m_Editor.Replace("15;#", "")
...?
It sounds like you want a regex of "at least one digit, then semi-colon and hash", with an anchor for "only at the start of the string":
string author = Regex.Replace(m_Author, @"^\d+;#", "");
Or to make it more reusable:
private static readonly Regex IdentifierMatcher = new Regex(@"^\d+;#");
...
string author = IdentifierMatcher.Replace(m_Author, "");
string editor = IdentifierMatcher.Repalce(m_Editor, "");
Note that there may be different appropriate solutions if:
You could use regex or (what i'd prefer) 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()函数使用#拆分字符串,这将为您提供两个字符串,首先是#之前的所有内容,然后是#之后的所有内容
use String.Format
int number=5;
string userId = String.Format("{0};#",number)
string author = m_Author.Replace(userId, "");
If all you want to do is filter out everything that is not a letter or space, try:
var originalName = "#123;Firstname Lastname";
var filteredName = new string(originalName
.Where(c => Char.IsLetter(c) ||
Char.IsWhiteSpace(c))
.ToArray());
The example will produce Firstname Lastname
List<char> originalName = "15;#Hans Meier".ToList();
string newString = string.Concat(originalName.Where(x => originalName.IndexOf(x) > originalName.IndexOf('#')).ToList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.