Tobias H.
Tobias H.

Reputation: 505

How to substring 0 to 30, but only if there is over 30 characters

I have a little problem, I want to substring a String, to max 30 characters, but when I do string.substring(0, 30), it works fine if the string is 30+ characters, but if not, it comes with an error.

Does anyone know how to fix that?

Upvotes: 3

Views: 3782

Answers (5)

atreeon
atreeon

Reputation: 24197

a bit shorter and without a check

string.characters.take(30)

enter image description here

Upvotes: 3

lava
lava

Reputation: 7451

import 'dart:math';
string.substring(0, min(30, string.length));

enter image description here

In the above picture, you can see that 2 variables below30 and above30

substring(int start, [int? end]);

when we use like this below30.substring(0,30) we get RangeError (end): Invalid value: Not in inclusive range 0..15: 30 error.Becasue below30 length is 15.above30 will give proper result because it have 32 character.

so overcoming this problem You can use like this:

string.substring(0, min(30, string.length));

min(num a, num b)=> Returns the lesser of two numbers. num (abstract class) may double or int.so here we didn't get any error invalid range.

enter image description here

For easy use you can use below30.characters.take(30) no more complexity. @@atreeon.

for bulk data manipulation substring method will much faster than takemethod

Build time: 3812 ms
Time substring: 391 ms, Time take: 1828 ms

Build time: 4172 ms
Time substring: 406 ms, Time take: 2141 ms

Upvotes: 6

Barsum
Barsum

Reputation: 156

import 'dart:math'; string.substring(0, min(30, string.length));

Upvotes: 0

Taha Malik
Taha Malik

Reputation: 2391

Try this

return string.substring(0, string.length < 30 ? string.length : 30);

Upvotes: 2

Levent KANTAROGLU
Levent KANTAROGLU

Reputation: 607

You should be getting "RangeError: Value not in range: 30" error.

Try to add a length control before that.

if (string.length < 30)

  return string;

else

  return string.substring(0, 30);

Let's shorten the code above:

String resultText = (string.length < 30) ? string : string.substring(0, 30);

Upvotes: 3

Related Questions