如何检查单词是否以给定字符开头? [英] How to check if a word starts with a given character?
问题描述
我有一个 Sharepoint 项目的列表:每个项目都有一个标题、一个描述和一个类型.我成功检索到它,我称它为result
.我想首先检查 result
中是否有任何以 A 开头的项目,然后是 B 然后是 C,等等.我必须对每个字母字符做同样的事情,然后如果我找到一个以开头的单词这个字符我将不得不以粗体显示该字符.
I have a list of a Sharepoint items: each item has a title, a description and a type.
I successfully retrieved it, I called it result
. I want to first check if there is any item in result
which starts with A then B then C, etc. I will have to do the same for each alphabet character and then if I find a word starting with this character I will have to display the character in bold.
我最初使用这个函数显示字符:
I initially display the characters using this function:
private string generateHeaderScripts(char currentChar)
{
string headerScriptHtml = "$(document).ready(function() {" +
"$("#myTable" + currentChar.ToString() + "") " +
".tablesorter({widthFixed: true, widgets: ['zebra']})" +
".tablesorterPager({container: $("#pager" + currentChar.ToString() +"")}); " +
"});";
return headerScriptHtml;
}
如何检查单词是否以给定字符开头?
How can I check if a word starts with a given character?
推荐答案
要检查一个值,请使用:
To check one value, use:
string word = "Aword";
if (word.StartsWith("A"))
{
// do something
}
你可以做一个小扩展方法来传递一个带有A、B和C的列表
You can make a little extension method to pass a list with A, B, and C
public static bool StartsWithAny(this string source, IEnumerable<string> strings)
{
foreach (var valueToCheck in strings)
{
if (source.StartsWith(valueToCheck))
{
return true;
}
}
return false;
}
if (word.StartsWithAny(new List<string>() { "A", "B", "C" }))
{
// do something
}
AND 作为奖励,如果您想从列表中知道您的字符串以什么开头,并根据该值执行某些操作:
AND as a bonus, if you want to know what your string starts with, from a list, and do something based on that value:
public static bool StartsWithAny(this string source, IEnumerable<string> strings, out string startsWithValue)
{
startsWithValue = null;
foreach (var valueToCheck in strings)
{
if (source.StartsWith(valueToCheck))
{
startsWithValue = valueToCheck;
return true;
}
}
return false;
}
用法:
string word = "AWord";
string startsWithValue;
if (word.StartsWithAny(new List<string>() { "a", "b", "c" }, out startsWithValue))
{
switch (startsWithValue)
{
case "A":
// Do Something
break;
// etc.
}
}
这篇关于如何检查单词是否以给定字符开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!