Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare each character of a String while accounting for characters with length > 1?

I have a variable string that might contain any unicode character. One of these unicode characters is the han 𩸽.

The thing is that this "han" character has "𩸽".length() == 2 but is written in the string as a single character.

Considering the code below, how would I iterate over all characters and compare each one while considering the fact it might contain one character with length greater than 1?

for ( int i = 0; i < string.length(); i++ ) {
    char character = string.charAt( i );
    if ( character == '𩸽' ) {
        // Fail, it interprets as 2 chars =/
    }
}

EDIT:
This question is not a duplicate. This asks how to iterate for each character of a String while considering characters that contains .length() > 1 (character not as a char type but as the representation of a written symbol). This question does not require previous knowledge of how to iterate over unicode code points of a Java String, although an answer mentioning that may also be correct.

like image 349
Fagner Brack Avatar asked Jun 07 '15 03:06

Fagner Brack


People also ask

How do I compare characters in a string?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

How do you compare two strings of different lengths?

if you use std::string, for comparison you can either use the compare function or use relational operators, provided with this class. if (str1 != str2) std::cout << "str1 and str2 are not equal\n"; all other relational operators, i.e., == < > <= >= are also available.

How do you compare string elements with characters?

strcmp() in C/C++ It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.

Can I use == to compare characters?

Yes, char is just like any other primitive type, you can just compare them by == .


1 Answers

int hanCodePoint = "𩸽".codePointAt(0);
for (int i = 0; i < string.length();) {
    int currentCodePoint = string.codePointAt(i);
    if (currentCodePoint == hanCodePoint) {
        // do something here.
    }
    i += Character.charCount(currentCodePoint);
}
like image 185
sstan Avatar answered Oct 13 '22 13:10

sstan