1

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
  • The issue can be your charset. It's because when I try .split('') in the first one, it returns � 12 times. I can't help, but you might focus on the charsets. Commented Nov 30, 2022 at 11:11
  • because of multi byte string. Commented Nov 30, 2022 at 11:33

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

instead of calling str.runes.toList() within the loop, store in a variable and then access within the loop..
@eamirho3ein, have you look this question please try to give answer of question
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.