detectDelimiter static method

String detectDelimiter(
  1. String content
)

Auto-detects the most likely delimiter from CSV content.

Implementation

static String detectDelimiter(String content) {
  if (content.isEmpty) return ',';

  // Look at the first line or first 1000 characters
  final firstLine = content.split(RegExp(r'\r\n|\r|\n')).firstWhere(
        (line) => line.trim().isNotEmpty,
        orElse: () => '',
      );

  if (firstLine.isEmpty) return ',';

  final candidates = [',', ';', '\t', '|'];
  int maxCount = -1;
  String bestDelimiter = ',';

  for (final delimiter in candidates) {
    int count = 0;
    bool insideQuote = false;
    for (int i = 0; i < firstLine.length; i++) {
      final char = firstLine[i];
      if (char == '"') {
        insideQuote = !insideQuote;
      } else if (!insideQuote && char == delimiter) {
        count++;
      }
    }
    if (count > maxCount) {
      maxCount = count;
      bestDelimiter = delimiter;
    }
  }

  return maxCount > 0 ? bestDelimiter : ',';
}