简体   繁体   中英

Check if string does contain text C#

I want to find a way to check if a string contains text and if it does it will go to to the next one and keep doing this till it finds an empty string or reached the end.

The issue is I can't find anything that I could use to check if the string is containing any text, I can only find if it a IsNullOrWhiteSpace or if it contains a specific text.

When does a string contain text? Well when the string exists and it does not contain an empty text. When does a string contain an empty text? When the length of the string is 0.

So, answering your question, a text is not empty when it exists and s.Length != 0 :

if (s != null && s.Length > 0) { /*s is not empty*/ }

or better yet

if (s?.Length > 0) { /*s is not empty*/ }

or if you prefer a string contains text when it is not nonexistant or empty:

if (!string.IsNullOrEmpty(s)) { /*s is not empty*/ }

Now if texts consisting only of whitespaces must also be considered as empty, then when is a text not empty? When the text is anything but nonexistant or empty spaces, that is, IsNullOrWhiteSpace is false :

if (!string.IsNullOrWhiteSpace(s)) { /*s is not empty*/ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM