开发者

How can I check if a string contains another string in C#

I have strings like this:

var a = "abcdef  * dddddd*jjjjjjjjjjjjj";
var b = "aaaaaaaaaaaaaaaaa开发者_如何学Pythonaaaaaaa * aaaaaa";
var c = "hhhhhhhhhhhhhhhhhhhhhhhhhhh";

Is there a smile way for me to check if the string contains a " * " within the first 20 characters?


Try this

a.IndexOf('*') >= 0 && a.IndexOf('*') < 20

Should work like a charm

Edit: IndexOf will also return -1 if the char wasn't found at all, which could be useful information i guess.


a.Substring(0, 20).Contains('*');


This will do it, but you should check the string length -- this code will fail if the string is too short:

bool b1 = a.Substring(0, 20).Contains('*');


bool contains = (a.Length > 20) ? a.Substring(0, 20).Contains("*") : a.Contains("*");

if(contains)
{
  etc...


Using Linq:

 a.Take(20).Contains('*')

This is the simplest and efficient than sub string based solution as it doesn't create new string object

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜