9

Say I have a string with n number of characters, but I want to trim it down to only 10 characters. (Given that at all times the string has greater that 10 characters) I don't know the contents of the string.

How to trim it in such a way?

I know how to trim it after a CERTAIN character

String s = "one.two";

//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);

But how to remove it after a CERTAIN NUMBER of characters?

7 Answers 7

21

All answers (using substring) get the first 10 UTF-16 code units, which is different than the first 10 characters because some characters consist of two code units. It is better to use the characters package:

import 'package:characters/characters.dart';

void main() {
  final str = "Hello 😀 World";

  print(str.substring(0, 9)); // BAD
  print(str.characters.take(9)); // GOOD
}

prints

➜ dart main.dart
Hello 😀 
Hello 😀 W

With substring you might even get half a character (which isn't valid):

print(str.substring(0, 7)); // BAD
print(str.characters.take(7)); // GOOD

prints:

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

Comments

8

The above examples will fail if string's length is less than the trimmed length. The below code will work with both short and long strings:

import 'dart:math';

void main() {
  String s1 = 'abcdefghijklmnop';
  String s2 = 'abcdef';


  var trimmed = s1.substring(0, min(s1.length,10));
  print(trimmed);
  
  trimmed = s2.substring(0, min(s2.length,10));
  print(trimmed);
}

NOTE: Dart string routines operate on UTF-16 code units. For most of Latin and Cyrylic languages that is not a problem since all characters will fit into a single code unit. Yet emojis, some Asian, African and Middle-east languages might need 2 code units to encode a single character. E.g. '😊'.length will return 2 although it is a single character string. See characters package.

Comments

3

I think this should work.

String result = s.substring(0, 10);

Comments

2

To trim a String to a certain number of characters. The. code below works perfectly well:

 // initialise your string here
  String s = 'one.two.three.four.five';

  // trim the string by getting the first 10 characters
  String trimmedString = s.substring(0, 10);

  // print the first ten characters of the string
  print(trimmedString);

Output:

one.two.th

i hope this helps

Comments

1

You can do this in multiple ways.

  1. 'string'.substr(start, ?length) USE :- 'one.two.three.four.five'.substr(0, 10)
  2. 'string'.substring(start, ?end) USE :- 'one.two.three.four.five'.substring(0, 10)
  3. 'string'.slice(start, ?end) USE :- 'one.two.three.four.five'.slice(0, 10)

Comments

1

To trim all trailing/right characters by specified characters, use the method:

  static String trimLastCharacter(String srcStr, String pattern) {   
    if (srcStr.length > 0) {   
      if (srcStr.endsWith(pattern)) { 
        final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
        return trimLastCharacter(v, pattern);
      } 
      return srcStr; 
    }   
    return srcStr;
  }

For example, you want to remove all 0 behind the decimals

$123.98760000

then, call it by

trimLastCharacter("$123.98760000", "0")

output:

$123.9876

Comments

0

It's not that hard if you understand how to work with Unicode characters properly. I won't say that this is the right way, but it works.

import 'package:sequence_processor/sequence_processor.dart';
import 'package:unicode/decomposers/canonical.dart';
import 'package:unicode/emoji/emoji.dart';

void main(List<String> args) {
  var str = 'hello🇵🇬你们😀😀👨‍👩‍👦';
  print('"$str"');
  while (str.isNotEmpty) {
    str = _removeChar(str, 1);
    print('"$str"');
  }

  str = 'I 💗 you! ❤️‍🔥 ';
  print('"$str"');
  while (str.isNotEmpty) {
    str = _removeChar(str, 1);
    print('"$str"');
  }

  str = 'Amélie';
  print('"$str"');
  while (str.isNotEmpty) {
    str = _removeChar(str, 1);
    print('"$str"');
  }

  str = "Hello 😀 World";
  print('"$str"');
  while (str.isNotEmpty) {
    str = _removeChar(str, 1);
    print('"$str"');
  }
}

// Should be stored in a static member for performance reasons.
final _processor = () {
  final emojis = getUnicodeEmojiList();
  final processor = SequenceProcessor<int, Object>();
  for (final emoji in emojis) {
    processor.addSequence(emoji.codePoints, emoji);
  }

  const decomposer = CanonicalDecomposer();
  final mappingList = decomposer.getMappingList();
  for (var i = 0; i < mappingList.length; i++) {
    final mapping = mappingList[i];
    final sequence = mapping.$2;
    if (sequence.length > 1) {
      if (!processor.hasSequence(sequence)) {
        processor.addSequence(mapping.$2, mapping.$1);
      }
    }
  }

  return processor;
}();

String _removeChar(String text, int count) {
  if (text.isEmpty) {
    return '';
  }

  final result = _processor.process(text.runes.toList());
  if (result.length < count) {
    return '';
  }

  return result
      .take(result.length - count)
      .map((e) => e.data == null
          ? String.fromCharCode(e.element!)
          : String.fromCharCodes(e.sequence!))
      .join();
}

Output:

"hello🇵🇬你们😀😀👨‍👩‍👦"
"hello🇵🇬你们😀😀"
"hello🇵🇬你们😀"
"hello🇵🇬你们"
"hello🇵🇬你"
"hello🇵🇬"
"hello"
"hell"
"hel"
"he"
"h"
""
"I 💗 you! ❤️‍🔥 "
"I 💗 you! ❤️‍🔥"
"I 💗 you! "
"I 💗 you!"
"I 💗 you"
"I 💗 yo"
"I 💗 y"
"I 💗 "
"I 💗"
"I "
"I"
""
"Amélie"
"Améli"
"Amél"
"Amé"
"Am"
"A"
""
"Hello 😀 World"
"Hello 😀 Worl"
"Hello 😀 Wor"
"Hello 😀 Wo"
"Hello 😀 W"
"Hello 😀 "
"Hello 😀"
"Hello "
"Hello"
"Hell"
"Hel"
"He"
"H"
""
""

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.