Test If Characters Are in a String

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.

Test if characters are in a string

Use the grepl function

grepl( needle, haystack, fixed = TRUE)

like so:

grepl(value, chars, fixed = TRUE)
# TRUE

Use ?grepl to find out more.

How can I check if character in a string is a letter? (Python)

You can use str.isalpha().

For example:

s = 'a123b'

for char in s:
print(char, char.isalpha())

Output:

a True
1 False
2 False
3 False
b True

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

Test if string ONLY contains given characters

Assuming the discrepancy in your example is a typo, then this should work:

my_list = ['aba', 'acba', 'caz']
result = [s for s in my_list if not s.strip('abc')]

results in ['aba', 'acba']. string.strip(characters) will return an empty string if the string to be stripped contains nothing but characters in the input. Order of the characters should not matter.

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


Related Topics



Leave a reply



Submit