好的,所以我的代码看起来有点像这样
// Returns the note of a favorite pown if it exists
string GetFavoriteNote(int id)
{
string notelist = Properties.Settings.Default.FavoriteNotesList;
// If there's a note, return it
if (notelist.Contains("'" + id + ":"))
{
// What to do here?
}
// If there's no note, return an empty string
else
{
return String.Empty;
}
}
现在它基本上是一个系统,用户可以为每个ID设置一个注释,它将以这种格式保存:'id:note','id:note'
,
现在我要做的是以某种方式选择该注释并将其返回,因此我必须选择从"'" + id + ":"
中选择直到'
如果有人知道怎么做,请帮帮我。 谢谢
答案 0 :(得分:3)
使用正则表达式对我来说似乎是最干净的方法:
string regexFormat = "'{0}:(.*?)'";
Match match = Regex.Match(notelist, string.Format(regexFormat, id));
return match.Success ? match.Groups[1].Value : string.Empty;
但是,您也可以使用字符串拆分:
var notes = notelist.Split(',');
var idString = "'" + id + ":";
var note = notes.FirstOrDefault(n => n.StartsWith(idString));
if (note == null) return string.Empty;
return note.Substring(idString.Length, note.Length - (idString.Length + 1));
答案 1 :(得分:0)
试
int StartIndex = notelist.IndexOf("'" + id.ToString() + ":");
string result = string.Empty;
if ( StartIndex >= 0 )
{
string tempstr = notelist.SubString ( StartIndex + ("'" + id.ToString() + ":").Length );
result = tempstr.SubString ( 0, tempstr.IndexOf ( "'" ) );
}
return result;
答案 2 :(得分:0)
到目前为止,我了解您的代码,以下代码将为您提供解决方案
string IdWithNote = string.Empty;
string noteList = Properties.Settings.Default.FavoriteNotesList;//your string type note list
List<string> listNote = new List<string>();//newly created string type collection
listNote=noteList.Split(',').ToList<string>();
int index=listNote.IndexOf("'" + id + ":");
if (index > -1)
IdWithNote = listNote[index];
return IdWithNote;
答案 3 :(得分:0)
老式的&amp;清除(无正则表达式)还假设您只需要注释的文本,而不是整个注释结构。
string key = "'" + id + ":";
int noteStart = noteList.IndexOf(key);
if (noteStart >= 0)
{
int textStart = noteStart + key.Length;
int textEnd = noteList.IndexOf("'", textStart);
return noteList.Substring(textStart, textEnd - textStart);
}
return "";
答案 4 :(得分:0)
var myId=2;
var t="'1:note1','2:note2'";
var query = t.Split(',').Select(c => c.Replace("'", "").Split(':')).
Where(c => c[0] == myId.ToString()).
Select(p=>p[1]).First();
答案 5 :(得分:0)
这里有一些代码 - 你真正想要的是:retVal = noteList.Substring(startIndex,endIndex - startIndex);
int id = 8;
string noteList = "'8:the note i want','81:the note i do not want'";
string toFind = "'" + id.ToString() + ":";
int startIndex = noteList.IndexOf(toFind) + toFind.Length;
int endIndex = noteList.IndexOf("'", startIndex);
if (noteList.Contains(toFind))
{
retVal = noteList.Substring(startIndex, endIndex - startIndex);
}
else
{
retVal = "nothing found";
}
答案 6 :(得分:-1)
notelist.Substring(notelist.IndexOf("'" + id + ":"), (notelist.IndexOf("'") - notelist.IndexOf("'" + id + ":")));
这应该可以做到,你可以通过子串将文本选择成新的字符串。 substring(startindex,lenght);