How can I check if a string contains a character in C#?

c string contains char
c program to search a string in an array
string search in c
strchr c
test if a string contains a substring c
strstr c
c check if string is alphabetic
check if string exists in string 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:

var abc = "s";
var def = "aB";
var ghi = "Sj";

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".

if (def.Somefunction("s") == true) { }

Also in C# do I need to check if something is true like this or could I just remove the "== true" ?

You can use the extension method .Contains() from the namespace System.Linq:

using System.Linq;

    ...

    if (abc.ToLower().Contains('s')) { }

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;:

if (abc.ToLower().IndexOf('s') != -1) { }

// or:

if (abc.IndexOf("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }

Update

If you want to, you can write your own extensions method for easier reuse:

public static class MyStringExtensions
{
    public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
    }

    public static bool ContainsAnyCase(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
    }
}

Then you can call them like this:

if (def.ContainsAnyCaseInvariant('s')) { }
// or
if (def.ContainsAnyCase('s')) { }

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).

How do I check if a string contains a certain character?, If you need to search for a character you can use the strchr function, like this: char​* pPosition = strchr(pText, '|');. pPosition will be NULL if the given character has  Use it inside for loop and check or the string that has special characters. Let us say our string is − string str = "Amit$#%"; Now convert the string into character array − str.ToCharArray(); With that, use a for loop and to check for each character using the isLetterOrDigit() method. Example. Let us see the complete code. Live Demo

You can use the IndexOf method, which has a suitable overload for string comparison types:

if (def.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0) ...

Also, you would not need the == true, since an if statement only expects an expression that evaluates to a bool.

How can I check if a single char exists in a C string?, If string containing 2 or more charecter that we want to find then it will print first left charecter How do I check whether a string contains a substring in C++?. The search begins at the first character position of this string and continues through the last character position. To determine whether a string contains a specified substring by using something other than ordinal comparison (such as culture-sensitive comparison, or ordinal case-insensitive comparison), you can create a custom method.

The following should work:

var abc = "sAb";
bool exists = abc.IndexOf("ab", StringComparison.CurrentCultureIgnoreCase) > -1;

How to write a program to check whether a given character is , How to Read and Write a Text File in C#? · How to Execute C# Program on cmd This method is used to check whether the substring occurs within a given  In C#, String.Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. This method is used to check whether the substring occurs within a given string or not.

bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;

C#, C++ program to find whether the string. // has all same characters or not. #include <iostream>. using namespace std;. bool allCharactersSame(string s). Instead of checking if a string contains "special characters" it is often better to check that all the characters in the string are "ordinary" characters, in other words use a whitelist instead of a blacklist.

Use the function String.Contains();

an example call,

abs.Contains("s"); // to look for lower case s

here is more from MSDN.

Quick way to check if all the characters of a string are same , #include <string.h> char *strchr(const char *string, int c); Copy The string arguments to the function should contain a null character (\0) that marks the end of  The methods HasWantedCharacters accept two or three strings. The first string we want to check for certain characters. The second string, all the characters that we'll look for in the first. The overloaded method provides output to the caller (ie Main) as a third string.

strchr(), To check if a string contains any special character, you need to use the following method IsLetterOrDigit(one[i])) { two[c] = one[i]; c++; } } Array. This works but the regular expression is inefficient. It will grab the first 7 characters and then test for "abc". If that test fails it will back up one character and try again. This process will continue until either a match is found or the beginning of the string is reached.

C# program to check if a string contains any special character, So for checking whether the substring is present into the main string, we have to check the return value of find() is string::npos or not. Here we are  This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found. you can also use Contains() , Contains is an instance method on the string type, which means you can call it on a specific string in your program.

Check if a string contains a sub-string in C++, Returns a value indicating whether a specified character occurs within this string, using To determine whether a string contains a specified substring by using  The string is also easier to scan than a series of character literals, IMO. Of course if you're only going to use this once, so the wasted creation isn't a problem, you could either use: private const string Punctuation = "*&#"; public static bool ContainsPunctuation(string text) { return text.IndexOfAny(Punctuation.ToCharArray()) >= 0; }

Comments
  • Hmm, I don't find a overload of String.Contains that takes a char argument.
  • @ScottSmith This is an extension method defined in System.Linq. You need to add using System.Linq;
  • I prefer to use str.IndexOf('s') >= 0 but it's probably just a stylistic difference. It makes more sense to me when reading for comprehension.
  • This does not answer the OPs question - they wanted to know whether an upper or lowercase "s" was present - your solution would only evaluate to true if a lowercase "s" was in the string.
  • MSDN doesn't list a Contains method that accepts a character, like in your first example. To get that syntax you'd need to use LINQ or write your own Contains extension.