How to Check a String for Specific Characters

How to check a string for specific characters?

Assuming your string is s:

'$' in s        # found
'$' not in s # not found

# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found

And so on for other characters.

... or

pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')

... or

chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')

[Edit: added the '$' in s answers]

How can I check if a single character appears in a string?

You can use string.indexOf('a').

If the char a is present in string :

it returns the the index of the first occurrence of the character in
the character sequence represented by this object, or -1 if the
character does not occur.

How do I check if a string contains a certain character?

By using strchr(), like this for example:

#include <stdio.h>
#include <string.h>

int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
if(strchr(str, '!') != NULL)
{
exclamationCheck = 1;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}

Output:

exclamationCheck = 1

If you are looking for a laconic one liner, then you could follow @melpomene's approach:

int exclamationCheck = strchr(str, '!') != NULL;

If you are not allowed to use methods from the C String Library, then, as @SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:

#include <stdio.h>

int main(void)
{
char str[] = "Hi, I'm odd";
int exclamationCheck = 0;
for(int i = 0; str[i] != '\0'; ++i)
{
if(str[i] == '!')
{
exclamationCheck = 1;
break;
}
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}

Output:

exclamationCheck = 0

Notice that you could break the loop when at least one exclamation mark is found, so that you don't need to iterate over the whole string.


PS: What should main() return in C and C++? int, not void.

How to tell if a string contains a certain character in JavaScript?

To find "hello" in your_string

if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression

most efficient way to check if a string contains specific characters

If I took the way you implement this, I would personally modify it like below:

private static void validate(String str) {
for (char c : str.toCharArray()) {
if ("{}()[]".indexOf(c) < 0){
throw new IllegalArgumentException("The string contains forbidden characters");
}
}
}

The changes are as follows:

  • Not declaring a temporary variable for the char array.
  • Using indexOf to find a character instead of converting c to String to use .contains().

  • Looping on the primitive char since you no longer need
    toString().

  • Not naming the parameter string as this can cause confusion and is not good practice.

Note: contains calls indexOf(), so this does also technically save you a method call each iteration.

Pattern to check if a string contains specific characters

You can use String.indexOf(int) to check if a specific character is in your string or not (it will return -1 if it's not in it).

You can use String.toCharArray() to get an array of all the characters you don't want and iterate this array per character.

Readable and simple code (though not most efficient) will be:

private static boolean charsOK(String s) { 
String charactersIdontWant = "^àáâãäåçèéêëìíîïðòóôõöùúûüýÿ!&{}¿?.<>~\\()";
for (char c : charactersIdontWant.toCharArray()) {
if (s.indexOf(c) != -1) return false;
}
return true;

}
public static void main(String[] args) {
String myString = "thisMayContïain/anything@";
String myString2 = "thisMayContain/anything@";
System.out.println(charsOK(myString));
System.out.println(charsOK(myString2));
}

Check if specific characters are in a string

Number of characters in chars1/chars2 that occur in s

That makes sense since you increment with an if condition. Since the if is not in a loop, you can increment it once.

Now we can unfold the generator into a for loop. This will solve one part of the problem and generate 0/6:

for c in chars1:
if c in s:
counter1 += 1

for c in chars2:
if c in s:

counter2 += 1

Nevertheless, this still will not be terribly efficient: it requires O(n) worst case to check if a character is in a string. You can construct a set first with the characters in the string, and then perform lookups (which are usually O(1) on average case:

def error_printer(s):
sset = set(s)
chars1 = "abcdefghijklm"
chars2 = "nopqrstuvwxyz"
counter1 = 0
counter2 = 0
for c in chars1:
if c in sset:
counter1 += 1
for c in chars2:
if c in sset:
counter2 += 1
print(str(counter2) + "/" + str(counter1))

Now we have improved the efficiency, but it is still not very elegantly: it takes a lot of code, and furthermore one has to inspect the code in order to know what it does. We can use a sum(..) construct to calculate the number of elements that satisfy a certain constraint like:

def error_printer(s):
sset = set(s)
chars1 = "abcdefghijklm"
chars2 = "nopqrstuvwxyz"
counter1 = sum(c in sset for c in chars1)
counter2 = sum(c in sset for c in chars2)

print(str(counter2) + "/" + str(counter1))

This produces 0/6 since there are six characters in the [A-M] range that occur in s and 0 in the [N-Z] range that occur in s.

Number of characters in s that occur in char1/char2

Based on the body of the question however, you want to count the number of characters in s that occur in the two different ranges.

An other related problem is counting the number of characters that occur in char1/char2. In that case we simply have to swap the loops:

def error_printer(s):
chars1 = set("abcdefghijklm")
chars2 = set("nopqrstuvwxyz")
counter1 = sum(c in chars1 for c in s)
counter2 = sum(c in chars2 for c in s)
print(str(counter2) + "/" + str(counter1))

This produces 0/14 since there are 14 characters in s that occur in the [A-M] range (if 'a' occurs twice in s, then we count it twice), and none of the characters in s occur in the [N-Z] range.

Using range checks

Since we are working with ranges, we can use comparisons instead of element checks, and make it run with two comparison checks, like:

def error_printer(s):
counter1 = sum('a' <= c <= 'm' for c in s)
counter2 = sum('n' <= c <= 'z' for c in s)
print(str(counter2) + "/" + str(counter1))

How to check if a string only contains certain characters in scala

val s: String = ???

s.forall("ab".contains)

forall checks whether a condition is true for all elements of a collection. So in this case it checks whether a condition is true for each character in s.

contains checks whether a string contains a character, so "ab".contains(x) checks whether x is either 'a' or 'b'.



Related Topics



Leave a reply



Submit