在这里有另一个强硬的人,基本上我想检查一个字符串是否包含单词“Foo”,如果它确实包含它,它是否从它开始?如果它确实以Foo开头,它应该是唯一以资本开头的Foo,其他所有都应该是小写字母。
如果满足上述条件,则应返回true。
如果字符串包含Foo但不以Foo开头,那么它应该立即返回false,因为你不能在字符串的中间有一个大写Foo。
如果所述字符串包含foo,但不以Foo开头,则foo的所有实例都应为小写。如果满足此条件,则返回true。
我应该提到我正在寻找C#代码,我尝试过但还没有成功,但由于我只编程了2周,所以我觉得这对你们这些季节专业人士来说不会有麻烦。
这就是我按照要求尝试过的,我认为它很平常,但至少我试过了。
if (Title.Contains("Foo") == true && Regex.IsMatch(Title, "^Foo") == true)
{
CheckAnd = true;
}
else if (Title.Contains("Foo") == true && Regex.IsMatch(Title, "^Foo") == false)
{
CheckAnd = false;
}
else if (Regex.IsMatch(Title, "^foo"))
{
CheckAnd = false;
}
else
{
CheckAnd = true;
}
好的,几乎在那里,这是我从你的所有答案得到的:
if (Title.IndexOf("Foo") == 0 && Title.LastIndexOf("Foo") == 0)
{
CheckAnd = true;
}
else if (Title.LastIndexOf("Foo") > 0)
{
CheckAnd = false;
}
else if(Title.Contains("foo") && Title.StartsWith("Foo") == false && PUT CHECK HERE)
我需要检查的是,在最后一个if语句中,所有出现的foo都是小写的吗?
答案 0 :(得分:6)
如果我理解正确,应该这样做!
if (testString.IndexOf("Foo") == 0 && testString.LastIndexOf("Foo") == 0)
// "Foo foo foo"
return true;
else if (testString.IndexOf("Foo") == 0 && testString.LastIndexOf("Foo") > 0)
// "Foo foo Foo"
return false;
else if (testString.Contains("foo") && testString.IndexOf("Foo") > 0)
// "foo Foo foo" or "foo foo Foo"
return false;
else if (testString.Contains("foo") && !testString.Contains("Foo"))
// "foo foo foo"
return true;
答案 1 :(得分:2)
这将返回true
(因为它包含单词Foo),然后false
(因为Foo不在句子的开头)。
string word = "I am a string i contain Foo, aint that nice?";
bool conts = word.Contains("Foo");
int pos = word.IndexOf("Foo");
if (conts)
{
if (pos != 0)
{
// do something
}
}
答案 2 :(得分:1)
请参阅String.IndexOf方法:
http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
搜索区分大小写,因此只需查找大写单词(例如:“Foo”)。如果IndexOf返回0,则该单词位于第一个位置。
编辑:我就是这样做的(看到你的代码之后)
//changed to check for lowercase foo
if ((Title.StartsWith("Foo") && Title.LastIndexOf("Foo") == 0)
|| (Title.Contains("foo") && !Title.StartsWith("foo")))
{
CheckAnd = true;
}
else
CheckAnd = false;
答案 3 :(得分:1)
如果我正确理解了这个问题,这个方法应该可行。
public bool ContainsFoo(string s)
{
bool result = true;
if (s.IndexOf("Foo") > 0)
{
result = false;
}
else if (s.LastIndexOf("Foo") > 0)
{
result = false;
}
return result;
}
如果我误解了某些内容,请告诉我。