user3910073
user3910073

Reputation: 531

R string containing only one type of character

I would like to check if a string contain only one type of character

For example

INPUT: 

str = "AAAAB"
char = "A"

OUTPUT:

str contains only char = FALSE

With grepl(char,str) the result is TRUE but I want it to be FALSE.

Many thanks

Upvotes: 5

Views: 1359

Answers (5)

David Arenburg
David Arenburg

Reputation: 92300

Using gregexpr

char = "A"

str = "AAAA"
length(unlist(gregexpr(char, str))) == nchar(str)
## [1] TRUE

str = "ABAAA"
length(unlist(gregexpr(char, str))) == nchar(str)
## [1] FALSE

Upvotes: 3

talat
talat

Reputation: 70326

If you want to check for a specific character (in char):

str <- "AAAAB"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] FALSE

str <- "AAAA"
char = "A"
all(unlist(strsplit(str, "")) == char)
#[1] TRUE

Or, if you want to check if the string contains only one unique character (any one):

str <- "AAAAB"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] FALSE

str = "AAAA"
length(unique(unlist(strsplit(str, "")))) == 1
#[1] TRUE

Upvotes: 5

agstudy
agstudy

Reputation: 121608

Another option is to use charToRaw and check if it is unique:

xx <- "AAAAB"
length(unique(charToRaw(xx))) ==1
[1] FALSE

Upvotes: 4

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193667

You can use the stri_count from the "stringi" package, like this:

library(stringi)
stri_count_fixed(str, char) == nchar(str)
# [1] FALSE

Upvotes: 3

m0nhawk
m0nhawk

Reputation: 24218

You need to use not operator for regex, in your case this would be:

> !grepl("[^A]", "AAA")
[1] TRUE
> !grepl("[^A]", "AAAB")
[1] FALSE

With variables:

grepl(paste0("[^", char, "]"), srt)

Upvotes: 4

Related Questions