How to Check If a Single Character Appears 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.

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 to check if some character appears in a string?

May be:

static boolean check(String str){
return str.matches("[CWRD]{4}") && str.chars().distinct().count() == 4;
}

Alternativly using only regex, but not that much readable:

static boolean check(String str){
return str.matches("(?!.*(.).*\\1)[CWRD]*");
}

Test:

public static void main(String[] args) {
String[] str = {"CDRW","CDWR","CRDW","CRWD","CWDR","CWRD",
"DCRW","DCWR","DRCW","DRWC","DWCR","DWRC",
"RCDW","RCWD","RDCW","RDWC","RWCD","RWDC",
"WCDR","WCRD","WDCR","WDRC","WRCD","WRDC"};
for(String s: str){
System.out.println(check(s));
}
}

Count the number of occurrences of a character in a string

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

Method to check if a Char is present on a specific String

You can use String.indexOf().

returns the index within this string of the first occurrence of the
specified character. If a character with value ch occurs in the
character sequence represented by this String object, then the index
(in Unicode code units) of the first such occurrence is returned, if
no such character occurs in this string, then -1 is returned.

 public static boolean find(String str, char ch){
if(str.indexOf(ch) == -1)
return false;
return true;
}

As you are thinking, you don't need four parameters for this function. You can use this function with two parameters for both cases:

  goal = find(first, firstChar);
goal = find(second, lastChar);

EDIT I think you have misunderstood the way the parameters are mapped.

if you have a function like

      public static boolean find(String str, char ch){
//do something
}

You don't need to call the find with same parameters str and ch, I mean find(str,ch). You can call them with any parameter, with any name, like :

        goal = find(s,c); // s is a string and c is a char

goal = find(a,b); // a is a string and b is a char

when you call find(s,c), s will be mapped to the first argument in your function that is str and c will be mapped to your second argument that is ch.

This is the reason you are able to call both find(first, firstChar) and find(second, lastChar) with a single function.

Simple way to count character occurrences in a string

public int countChar(String str, char c)
{
int count = 0;

for(int i=0; i < str.length(); i++)
{ if(str.charAt(i) == c)
count++;
}

return count;
}

This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.

efficiently checking that string consists of one character in Python

This is by far the fastest, several times faster than even count(), just time it with that excellent mgilson's timing suite:

s == len(s) * s[0]

Here all the checking is done inside the Python C code which just:

  • allocates len(s) characters;
  • fills the space with the first character;
  • compares two strings.

The longer the string is, the greater is time bonus. However, as mgilson writes, it creates a copy of the string, so if your string length is many millions of symbols, it may become a problem.

As we can see from timing results, generally the fastest ways to solve the task do not execute any Python code for each symbol. However, the set() solution also does all the job inside C code of the Python library, but it is still slow, probably because of operating string through Python object interface.

UPD: Concerning the empty string case. What to do with it strongly depends on the task. If the task is "check if all the symbols in a string are the same", s == len(s) * s[0] is a valid answer (no symbols mean an error, and exception is ok). If the task is "check if there is exactly one unique symbol", empty string should give us False, and the answer is s and s == len(s) * s[0], or bool(s) and s == len(s) * s[0] if you prefer receiving boolean values. Finally, if we understand the task as "check if there are no different symbols", the result for empty string is True, and the answer is not s or s == len(s) * s[0].

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.



Related Topics



Leave a reply



Submit