- How can I check if a string contains a character in C#?
- 8 Answers 8
- VB.NET — If string contains “value1” or “value2”
- 9 Answers 9
- How to determine if string contains specific substring within the first X characters
- 10 Answers 10
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to check if string contains the text in C# Winforms
- 4 Answers 4
- Checking If a String Contains a Word and Then Checking If It Starts With said Word and If It Doesnt?
- 5 Answers 5
- Don’t want to read my book? Here’s the answer:
- Read on for a lessons in coding logic (humor this old man)
- Step 1
- Step 2
- Output:
- Results and Conclusions
How can I check if a string contains a character in C#?
Is there a function I can apply to a string that will return true of false if a string contains a character.
I have strings with one or more character options such as:
What I would like to do for example is have a function that would return true or false if the above contained a lower or upper case «s».
Also in C# do I need to check if something is true like this or could I just remove the «== true» ?
8 Answers 8
You can use the extension method .Contains() from the namespace System.Linq:
And no, to check if a boolean expression is true, you don’t need == true
Since the Contains method is an extension method, my solution appeared to be confusing to some. Here are two versions that don’t require you to add using System.Linq; :
Update
If you want to, you can write your own extensions method for easier reuse:
Then you can call them like this:
In most cases when dealing with user data, you actually want to use CurrentCultureIgnoreCase (or the ContainsAnyCase extension method), because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.
For example: In Turkish, the uppercase letter I in lowercase is ı (without a dot), and not i (with a dot).
VB.NET — If string contains “value1” or “value2”
I’m wondering how I can check if a string contains either «value1» or «value2»? I tried this:
This works, but this doesn’t:
This gives me the error that conversion from string to Long can’t be done. If I put the or («Something2») inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.
So how can I check if the string contains either «string1» or «string2» without having to write too much code?
9 Answers 9
You have to do it like this:
In addition to the answers already given it will be quicker if you use OrElse instead of Or because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:
NOTE: This solution has been tested with Visual Studio 2010.
You have («Something2») by itself — you need to test it so a boolean is returned:
The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won’t work.
I’ve approached this in a different way. I’ve created a function which simply returns true or false.. Usage:
If FieldContains(«A;B;C»,MyFieldVariable,True|False) then
How to determine if string contains specific substring within the first X characters
I want to check whether Value1 below contains «abc» within the first X characters. How would you check this with an if statement?
It could be within the first 3, 4 or 5 characters.
10 Answers 10
Or if you need to set the value of found:
Edit: Given your edit, I would do something like:
I would use one of the of the overloads of the IndexOf method
sorry, but I am a stickler for ‘less’ code.
Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith
Use IndexOf is easier and high performance.
This is what you need :
You’re close. but use: if (Value1.StartsWith(«abc»))
A more explicit version is
It’s best to always explicitly list the particular comparison you are doing. The String class can be somewhat inconsistent with the type of comparisons that are used.
You can also use regular expressions (less readable though)
Adding on from the answer below i have created this method:
it can be used like this:
you can check for multiple invalid values this way.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to check if string contains the text in C# Winforms
Can anyone help me in writing a piece of code in C# Winforms, which can give me a boolean value, that whether a piece of string contains a few words.
For example, If I want to check whether string test only string exists in string «Data is provided to test only string».
I have written following piece of code, but it alwys gives me true, whether string contains the words or nor.
When I call the following line, I always get true, which is not correct
4 Answers 4
You can use Contains method of String object.
Code-wise, your ContainsText code immediately returns true if any character in input is either in «A to Z» or «a to U+00B1» for some reason.
But the problems lie deeper than that: you’ve described two inputs — the string to check for, e.g. «test only string» and the string to check for its presence, e.g. «Data is provided to test only string». Your method only accepts one input, and doesn’t use any other state. So it can’t possibly work. It’s worth taking a step back and trying to work out why you didn’t notice that you needed two inputs — and why indeed your test only used «test only string» and didn’t mention «Data is provided to test only string».
You don’t really need a method at all though — String already has a Contains method:
That’s assuming you want an ordinal comparison. Use IndexOf with an appropriate StringComparison if you want to check in a culture-sensitive or case-insensitive way.
Checking If a String Contains a Word and Then Checking If It Starts With said Word and If It Doesnt?
Having another tough one here guys, basically I would like to check if a string contains the word «Foo» and if it does contain it, does it start with it? If it does start with Foo, it should be the only Foo that starts with a capital, all others should be small letters.
If the above criteria is met, it should return true.
If the string contains Foo but doesn’t start with Foo, it should immediately return false since you cant have a capital Foo in the middle of the string.
In the event that said string contains foo, but doesn’t start with Foo, all instances of foo should be lowercase. If this criteria is met, return true.
I should mention i am looking for C# code, I tried and have not yet succeeded, but since I have only been programming for 2 weeks, I don’t think this will be trouble for some of you season pro’s.
This is what I have tried as requested, I thinks its faaar off but at least I tried.
Ok guys, nearly there, this is what I got from all your answers:
The last thing I need to check that all occurrences of foo are lowercase in the last else if statement ?
5 Answers 5
If I undestood it correctly this should do it !
Don’t want to read my book? Here’s the answer:
As a bonus, this is the fastest performing solution.
Read on for a lessons in coding logic (humor this old man)
This question may be old, but for the sake of those finding this question later who are curious about how to logically distill word problems (so please don’t downvote this lurker who finally decided to post), here’s my massively overdone analysis for this extremely simple homework assignment:
I ran a set of tests to see what options were the fastest — this often helps me see flaws in my logic. I am also going to explain my thought process, since, IMHO, understanding how to distill a problem to it’s core logic is a good thing to know for real world use.
After all, that’s what Business Requirements Docs are. word problems that need to be distilled into functional specs (e.g. architectural design).
Step 1
Eliminate Extraneous Information
Based on the requirements given, lower case foo may or may not matter: There is no explicit statement that a string not containing foo and not containing Foo should return false; There is also no explicit statement that says a string not containing Foo and not containing foo should return true.
In a perfect world, you would go back for clarification on the requirements, but in some cases, there isn’t time. Assuming there is a deadline, I would move forward with the assumption that all we care about is Foo being uppercase only when in the first position in the sentence, lower case at all other times, so we will ignore foo altogether, and if the «client» complains, point out the missing clarity and explain why you made a judgement call (to keep the project on time, and on budget, if applicable).
Step 2
Break down the logic into OR/AND pieces:
Breaking Foo into components lets us look at individual pieces, which can be easier than looking at the whole. So, if we break the string into «stuff before Foo» (even if that is «nothing») and «stuff after Foo» OR if Foo isn’t there to break up the string, we only have one piece to look at. (Our brains do this all the time — it’s called pattern recognition).
IF The string cannot be split because Foo is not found
OR
splitting on Foo gives us no more than two pieces: nothing before, and everything after
AND (implied by the previous check only finding an empty «before» and only one «section» in the «after») Foo is not found anywhere else in the string
Sound good? Well, it’s 100% accurate, but we can cut some cruft and distill it further — keep in mind computers don’t think like humans, so our mental processing is inefficient for them.
Because Foo not being found at all is considered valid, and Foo at the beginning is valid, but Foo anywhere else later in the string is invalid, we can say:
IF Foo is not found
OR
Foo is not found anywhere in the string past the first position
Seems tight, right? Don’t stop now. We can do better.
If Foo is found at the beginning, we’re fine with it, right? So «Foo is not Found» OR «Foo is found at the beginning AND Foo is not found anywhere else» can be looked at from a more pure logic (boolean, true/false, black and white) perspective:
- LET FNA = «Foo is not found anywhere»
- LET FN1 = «Foo is not found in position 1»
- LET FN2 = «Foo is not found after position 1»
- LET FF1 = «Foo is found in position 1»
- LET FF2 = «Foo is found after position 1»
So now define as invalid only those cases which are guaranteed invalid, and mark the rest as valid. We’ll use boolean math to determine all use cases.
- LET FNA = valid
- LET FN1 = valid
- LET FN2 = valid
- LET FF1 = valid
- LET FF2 = invalid
Now that we’ve labeled only the cases that absolutely force a return of false, we can do the math to see the only cases where we get an invalid/false value.
FNA and/or FF1 = true, so we know that all combinations of and/or of these 4 variables = true; This leaves only one variable left to combine, and we can see really quickly that FF2 and anything will always be false.
So translated back into human logic. see how much simpler this task is?
ONLY FALSE IF Foo is found after position 1
Or, to flip the boolean (since the requirements say to return true for valid cases):
IF Foo is NOT found after position 1, string is valid.
Or, to put it more like a computer’s thinking:
IF scanning from the end of the string until the 2nd to the last character does not find Foo, string is valid
There, now we can’t distill it any further down. So let’s code these different bits of logic and see how they perform in real code:
Output:
Results and Conclusions
Test A (human logic of visually splitting on/counting the words found), compared to test B (scanning using indexes with the distilled logic), Test A runs over 220% longer!
Test C is the best performer — only one scan of the string needed. Coming in at less than 30% the processing time required (Test A takes over 340%! of the amount of time Test C requires to complete the same work).
So hopefully some student somewhere has read this and the lightbulb goes on. You can always come up with ways to make stuff that «works», but understanding boolean logic and how to distill a concept down to it’s core can make a significant impact on the quality of your work.