You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中无需按回车键逐个读取字符串输入字符?

Dart 逐字符读取输入替代整行读取

原代码通过stdin.readLineSync()一次性读取整行再分割,现在修改为逐字符读取输入,实现相同的逻辑:

import 'dart:io';

void main() {
  // 读取初始计数(此处仍用整行读取,因计数为单个整数)
  int counter = int.parse(stdin.readLineSync() ?? '0');
  
  while (counter > 0) {
    List<String> numbers = [];
    String currentNumber = '';
    
    // 逐字符读取直到收集到两个数字
    while (numbers.length < 2) {
      // 读取单个字节并转换为Unicode字符
      int byte = stdin.readByteSync();
      if (byte == -1) break; // 输入流结束
      
      String char = String.fromCharCode(byte);
      
      // 处理空白字符(空格、换行等)
      if (RegExp(r'\s').hasMatch(char)) {
        // 若当前已有收集的字符,视为一个数字结束
        if (currentNumber.isNotEmpty) {
          numbers.add(currentNumber);
          currentNumber = '';
        }
      } else {
        // 非空白字符追加到当前数字字符串
        currentNumber += char;
      }
    }
    
    // 处理输入末尾无空白字符的情况,确保最后一个数字被收集
    if (currentNumber.isNotEmpty && numbers.length < 2) {
      numbers.add(currentNumber);
    }
    
    // 原业务逻辑部分
    String first = numbers[0];
    String second = numbers[1];
    if (second.length > first.length) {
      print("nao encaixa");
    } else if (first == second) {
      print("encaixa");
    } else if (first.substring(first.length - second.length) == second) {
      print("encaixa");
    } else {
      print("nao encaixa");
    }
    
    counter--;
  }
}

关键修改说明:

  • 用stdin.readByteSync()逐个读取输入字节,通过String.fromCharCode()转换为字符
  • 循环处理每个字符:遇到空白字符时,若已收集数字字符则存入列表;非空白字符追加到当前数字字符串
  • 补充处理输入末尾无空白字符的场景,避免遗漏最后一个数字
  • 初始计数保留整行读取,因它是单个整数,逐字符读取此处无必要

内容的提问来源于stack exchange,提问作者diaa serag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:22:09