Shalugin
Shalugin

Reputation: 1204

Flutter - Remove String after certain character?

What is the best way to remove all characters after specific character in the String object in Flutter?

Suppose that I have the following string:

one.two

and I need to remove the ".two" from it. How can I do it?

Thanks in advance.

Upvotes: 33

Views: 76486

Answers (7)

ajaybadole
ajaybadole

Reputation: 155

var regex = RegExp(r'.[a-z]*$');
String s='one.two';
print(s.replaceAll(regex,''));

Upvotes: 0

android Professional
android Professional

Reputation: 71

String str = "one.two";
  print(str.replaceAll(".two", ""));

Upvotes: 1

hararot so
hararot so

Reputation: 161

The answer is above but here is how you can do it if you want only certain character position or location.

To get substring from a Dart String, we use substring() method:

String str = 'bezkoder.com';

// For example, here we want ‘r’ is the ending. In ‘bezkoder.com’,
// the index of ‘r’ is 7. So we need to set endIndex by 8.
str.substring(0,8); // bezkoder

str.substring(2,8); // zkoder
str.substring(3);   // koder.com

This is the signature of substring() method that returns a String:

String substring(int startIndex, [int endIndex]);

startIndex: index of character to start with. Beginning index is 0. endIndex (optional): index of ending character + 1. If it is not set, the result will be a subtring starting from startIndex to the end of the string.

[Reference] [1]: https://bezkoder.com/dart-string-methods-operators-examples/

Upvotes: 8

Rageh Azzazy
Rageh Azzazy

Reputation: 757

Here is a full working code that combines all above solutions

Maybe my syntax writing and splitting code is not common,, sorry for that I'm self taught beginner

// === === === === === === === === === === === === === === === === === === ===
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

/// in case you are saving assets in flutter project folder directory like this
/// 'assets/xyz/somFolder/image.jpg'
/// And u have a separate class where u save assets in variables like this to easily call them in your widget tree
/// 
/// class SuperDuperAsset {
///   static const String DumAuthorPic = 'assets/dum/dum_author_pic.jpg' ;
///   static const String DumBusinessLogo = 'assets/dum/dum_business_logo.jpg' ;
///   }
///   
/// I just want to insert SuperDuperAsset.DumBusinessLogo in this function below
/// 
/// and here is a fix and a combination for all mentioned solutions that works like a charm in case you would like to copy paste it
/// and just use this function like this
/// 
/// File _imageFile = await getImageFileFromAssets(SuperDuperAsset.DumBusinessLogo);
/// and you are good to go
/// 
/// some other functions that manipulate the asset path are separated below
Future<File> getImageFileFromAssets(String asset) async {
  
  String _pathTrimmed = removeNumberOfCharacterFromAString(asset, 7);
  
  final _byteData = await rootBundle.load('assets/$_pathTrimmed');
  
  final _tempFile = File('${(await getTemporaryDirectory()).path}/${getFileNameFromAsset(_pathTrimmed)}');
  
  await _tempFile.writeAsBytes(_byteData.buffer.asUint8List(_byteData.offsetInBytes, _byteData.lengthInBytes));
  
  _tempFile.create(recursive: true);
  
  return _tempFile;

}
// === === === === === === === === === === === === === === === === === === ===
String removeNumberOfCharacterFromAString(String string, int numberOfCharacters){
  String _stringTrimmed;
  if (numberOfCharacters > string.length){
    print('can not remove ($numberOfCharacters) from the given string because : numberOfCharacters > string.length');
    throw('can not remove ($numberOfCharacters) from the given string because');
  } else {
    _stringTrimmed = string.length >0 ? string?.substring(numberOfCharacters) : null;
  }
  return _stringTrimmed;
}
// === === === === === === === === === === === === === === === === === === ===
/// this trims paths like
/// 'assets/dum/dum_business_logo.jpg' to 'dum_business_logo.jpg'
String getFileNameFromAsset(String asset){
  String _fileName = trimTextBeforeLastSpecialCharacter(asset, '/');
  return _fileName;
}
// === === === === === === === === === === === === === === === === === === ===
String trimTextBeforeLastSpecialCharacter(String verse, String specialCharacter){
  int _position = verse.lastIndexOf(specialCharacter);
  String _result = (_position != -1)? verse.substring(_position+1, verse.length): verse;
  return _result;
}
// === === === === === === === === === === === === === === === === === === ===

Upvotes: 0

You can use the subString method from the String class

String s = "one.two";

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

In case there are more than one '.' in the String it will use the first occurrance. If you need to use the last one (to get rid of a file extension, for example) change indexOf to lastIndexOf. If you are unsure there is at least one occurrance, you should also add some validation to avoid triggering an exception.

String s = "one.two.three";

//Remove everything after last '.'
var pos = s.lastIndexOf('.');
String result = (pos != -1)? s.substring(0, pos): s;
print(result);

Upvotes: 63

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15053

String str = "one.two";
var value = str?.replaceFirst(RegExp(r"\.[^]*"), "");

You can use str.substring(0, str.indexOf('.')); if you sure str contains .

Otherwise you will get error Value not in range: -1.

Upvotes: 8

Blasanka
Blasanka

Reputation: 22437

void main() {
  String str = "one.two";
  print(str.replaceAll(".two", ""));

  // or

  print(str.split(".").first);

  // or

  String newStr = str.replaceRange(str.indexOf("."), str.length, "");
  print(newStr);


  // Lets do a another example

  String nums = "1,one.2,two.3,three.4,four";
  List values = nums.split("."); // split() will split from . and gives new List with separated elements.
  values.forEach(print);

  //output

//   1,one
//   2,two
//   3,three
//   4,four
}

Edit this in DartPad.

Actually, there are other cool methods in String. Check those here.

Upvotes: 16

Related Questions