开发者

c# strings manipulation

I have the following code where frequencyOfReminders = "2 days"

 dailyReminders = frequencyOfReminders.IndexOf("day", StringComparison.OrdinalIgnoreCase) >= 0;

I want dailyReminders to be true should I use the below instead?

 dailyReminders = frequencyOfReminders.Contains("day", StringComparison.OrdinalIgnoreCase) >= 0;

I should have been clearer. I have the string frequencyOfReminders= "2 days" for e开发者_如何学JAVAg and I want dailyreminders to return true if it finds the string "day" in frequencyOfReminders, other values where it would return true are : daily, 3 days, 1 day, ... etc


The String.Contains method returns a boolean, so the >= 0 won't compile.

Should be like this:

dailyReminders = frequencyOfReminders.Contains("day", StringComparison.OrdinalIgnoreCase);

However, in this case I would lean towards Contains for readability.

Edit:

Oh, you're searching for multiple search terms. In that case, one way to do it is with multiple Contains calls (straightforward):

dailyReminders = frequencyOfReminders.Contains("day", StringComparison.OrdinalIgnoreCase)
                 || frequencyOfReminders.Contains("daily", StringComparison.OrdinalIgnoreCase);

Another way is to get into regular expressions (fully explaining this approach will take some work), but here is a link that explains it:

http://www.regular-expressions.info/dotnet.html

Regular expressions are incredibly powerful, but there is a learning curve.


dailyReminders = frequencyOfReminders.Contains("day", StringComparison.OrdinalIgnoreCase)

does not requires >=0. In both cases the result is the same.


Yes, but you should omit the '>=0' comparison when you use the .contains method. String.Contains(,) already returns a boolean:

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx


The string function "Contains" does return a boolean, so something like

boolean dailyReminders = frequencyOfReminders.Contains("day");

would set dailyReminders to true.


IndexOf returns -1 when the substring was not found so :

dailyReminders = frequencyOfReminders.IndexOf("day", StringComparison.OrdinalIgnoreCase) != -1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜