【问题标题】:Flutter - Remove String after certain character?Flutter - 在某个字符后删除字符串?
【发布时间】:2020-01-16 06:00:55
【问题描述】:

在 Flutter 中删除 String 对象中特定字符之后的所有字符的最佳方法是什么?

假设我有以下字符串:

一二

我需要从中删除“.two”。我该怎么做?

提前致谢。

【问题讨论】:

  • 问题:这样做的目的是为了从文件名中删除扩展名吗?

标签: flutter dart


【解决方案1】:

您可以使用String 类中的subString 方法

String s = "one.two";

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

如果有多个 '.'在String 中,它将使用第一次出现。如果您需要使用最后一个(例如去除文件扩展名),请将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);

【讨论】:

  • 为了让它更简单,用's'作为初始字符串one.two然后s.substring(0, s.indexOf('.'))产生:ones.substring(s.indexOf('.') + 1)产生:two
【解决方案2】:
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
}

DartPad 中编辑。

其实String里还有其他很酷的方法。检查那些here

【讨论】:

    【解决方案3】:
    String str = "one.two";
    var value = str?.replaceFirst(RegExp(r"\.[^]*"), "");
    

    如果您确定str 包含.,则可以使用str.substring(0, str.indexOf('.'));

    否则会报错Value not in range: -1

    【讨论】:

    • 您可以使用[^] 匹配所有字符,而不是使用(.|\s)[\s\S] 或其他变通方法。那么正则表达式可能只是r"\.[^]*"
    • @Irn 哦...谢谢 :)
    【解决方案4】:

    答案在上面,但是如果你想要只需要特定的角色位置或位置,你可以这样做。

    要从 Dart 字符串中获取子字符串,我们使用 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); // bezkoder
    
    str.substring(2,8); // zkoder
    str.substring(3);   // koder.com
    

    这是返回字符串的substring() 方法的签名:

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

    startIndex:开始的字符索引。起始索引为 0。 endIndex(可选):结束字符的索引 + 1。如果不设置,结果将是从 startIndex 开始到字符串末尾的子字符串。

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

    【讨论】:

      【解决方案5】:

      这是一个完整的工作代码,结合了上述所有解决方案

      也许我的语法编写和拆分代码不常见,对不起,我是自学成才的初学者

      // === === === === === === === === === === === === === === === === === === ===
      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;
      }
      // === === === === === === === === === === === === === === === === === === ===
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        相关资源
        最近更新 更多