skip to Main Content

I am working on application to show mobile contact list with initials in a circle, but not getting initial character for some contact names.

In below code, first name is from mobile’s contact list and second one I have typed from keyboard.
I am able to get correct length and also first character of the second name, but length for first name is double and also not able to get first character (it gives �).

print("𝙽𝚊𝚐𝚎𝚜𝚑".substring(0,1)); //�
print("𝙽𝚊𝚐𝚎𝚜𝚑".length); //12
  
print("Nagesh".substring(0,1)); //N
print("Nagesh".length); //6

Thankyou in advance for answering….

2

Answers


  1. The strings look similar, but they consist of different unicode characters.

    Character U+1d67d "𝙽" is not the same as U+004e "N".
    You can use str.runes.length to get the number of unicode characters.

    A detailed explanation why the string length is different can be found here

    example:

    void main() {
      var mobileStr = "𝙽𝚊𝚐𝚎𝚜𝚑";
      var keyboardStr = "Nagesh";
    
      analyzeString(mobileStr);
      print("");
      analyzeString(keyboardStr);
    }
    
    void analyzeString(String s) {
      Runes runes = s.runes; // Unicode code-points of this string
      var unicodeChars = runes.map((r) => r.toRadixString(16)).toList();
    
      print("String: $s");
      print("String length: ${s.length}");
      print("Number of runes: ${runes.length}");
      print("unicode characters: ${unicodeChars.join(" ")}");
    }
    
    // OUTPUT
    // String: 𝙽𝚊𝚐𝚎𝚜𝚑
    // String length: 12
    // Number of runes: 6
    // unicode characters: 1d67d 1d68a 1d690 1d68e 1d69c 1d691
    
    // String: Nagesh
    // String length: 6
    // Number of runes: 6
    // unicode characters: 4e 61 67 65 73 68
    
    Login or Signup to reply.
  2. You can use this function to use substring with unicode:

    subOnCharecter({required String str, required int from, required int to}) {
        var runes = str.runes.toList();
        String result = '';
        for (var i = from; i < to; i++) {
          result = result + String.fromCharCode(runes[i]);
        }
        return result;
      }
    

    and you can use it like this:

    print(subOnCharecter(str: "𝙽𝚊𝚐𝚎𝚜𝚑", from: 0, to: 2)); // 𝙽𝚊
    print(subOnCharecter(str: "Nagesh", from: 0, to: 2)); // Na
    

    you can use this function instead of default substring.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search