在Flutter中删除String对象中特定字符之后的所有字符的最佳方法是什么?假设我有以下字符串:one.two我需要把“. 2”去掉,怎么做先谢了。
xxhby3vn1#
可以使用String类中的subString方法
String
subString
String s = "one.two";//Removes everything after first '.'String result = s.substring(0, s.indexOf('.'));print(result);
String s = "one.two";
//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);
字符串如果String中有多个“.”,它将使用第一次出现的“.”。如果您需要使用最后一个“.”(例如,为了摆脱文件扩展名),请将indexOf更改为lastIndexOf。如果您不确定至少有一个“.”,则还应添加一些验证以避免触发异常。
indexOf
lastIndexOf
String s = "one.two.three";//Remove everything after last '.'var pos = s.lastIndexOf('.');String result = (pos != -1)? s.substring(0, pos): s;print(result);
String s = "one.two.three";
//Remove everything after last '.'
var pos = s.lastIndexOf('.');
String result = (pos != -1)? s.substring(0, pos): s;
型
iqjalb3h2#
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}
void main() {
String str = "one.two";
print(str.replaceAll(".two", ""));
// or
print(str.split(".").first);
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
}
字符串在DartPad中编辑此内容。实际上,在String中还有其他很酷的方法。看看那些here。
p4rjhz4m3#
String str = "one.two";var value = str?.replaceFirst(RegExp(r"\.[^]*"), "");
var value = str?.replaceFirst(RegExp(r"\.[^]*"), "");
字符串如果确定str包含.,则可以使用str.substring(0, str.indexOf('.'));否则,您将得到错误Value not in range: -1。
str
.
str.substring(0, str.indexOf('.'));
Value not in range: -1
iqxoj9l94#
答案在上面,但这里是你如何做到这一点,如果你想只有某些字符的位置或位置。为了从Dart String中获取子字符串,我们使用substring()方法:
substring()
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); // bezkoderstr.substring(2,8); // zkoderstr.substring(3); // koder.com
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
字符串这是返回String的substring()方法的签名:
String substring(int startIndex, [int endIndex]);
型startIndex:开始字符的索引。开始索引为0。endIndex(可选):结束字符的索引+ 1。如果不设置,结果将是从startIndex开始到字符串结尾的减法。[参考] [1]:https://bezkoder.com/dart-string-methods-operators-examples/
startIndex
endIndex
sdnqo3pr5#
String str = "one.two"; print(str.replaceAll(".two", ""));
字符串
wz8daaqr6#
这里是一个完整的工作代码,结合了所有上述解决方案也许我的语法编写和分割代码是不常见的,,对不起,我自学初学者
// === === === === === === === === === === === === === === === === === === ===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 belowFuture<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;}// === === === === === === === === === === === === === === === === === === ===
// === === === === === === === === === === === === === === === === === === ===
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;
o0lyfsai7#
var regex = RegExp(r'.[a-z]*$');String s='one.two';print(s.replaceAll(regex,''));
var regex = RegExp(r'.[a-z]*$');
String s='one.two';
print(s.replaceAll(regex,''));
7条答案
按热度按时间xxhby3vn1#
可以使用
String
类中的subString
方法字符串
如果
String
中有多个“.”,它将使用第一次出现的“.”。如果您需要使用最后一个“.”(例如,为了摆脱文件扩展名),请将indexOf
更改为lastIndexOf
。如果您不确定至少有一个“.”,则还应添加一些验证以避免触发异常。型
iqjalb3h2#
字符串
在DartPad中编辑此内容。
实际上,在
String
中还有其他很酷的方法。看看那些here。p4rjhz4m3#
字符串
如果确定
str
包含.
,则可以使用str.substring(0, str.indexOf('.'));
否则,您将得到错误
Value not in range: -1
。iqxoj9l94#
答案在上面,但这里是你如何做到这一点,如果你想只有某些字符的位置或位置。
为了从Dart String中获取子字符串,我们使用
substring()
方法:字符串
这是返回String的
substring()
方法的签名:型
startIndex
:开始字符的索引。开始索引为0。endIndex
(可选):结束字符的索引+ 1。如果不设置,结果将是从startIndex开始到字符串结尾的减法。[参考] [1]:https://bezkoder.com/dart-string-methods-operators-examples/
sdnqo3pr5#
字符串
wz8daaqr6#
这里是一个完整的工作代码,结合了所有上述解决方案
也许我的语法编写和分割代码是不常见的,,对不起,我自学初学者
字符串
o0lyfsai7#
字符串