2

I have strings like this:

var a = "abcdef  * dddddd*jjjjjjjjjjjjj";
var b = "aaaaaaaaaaaaaaaaaaaaaaaa * aaaaaa";
var c = "hhhhhhhhhhhhhhhhhhhhhhhhhhh";

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

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You forgot to also check for > -1
3
a.Substring(0, 20).Contains('*');

1 Comment

This will throw an ArgumentOutOfRangeException if the string has a length less than 20.
2

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('*');

Comments

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

if(contains)
{
  etc...

2 Comments

This will throw an ArgumentOutOfRangeException if the string has a length less than 20.
@Jk - I tried all the solutions but there is a problem. What if the line is less than 20 characters long?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.