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

如何用C++统计TXT文件中的数据列数?

Got it, let's tackle this problem. You need a function that counts the number of columns in space/tab-separated text (like your TXT or Excel-exported data) and returns an integer. Here's a practical, edge-case-friendly solution with examples for common languages:

Count Columns in Space/Tab-Separated Text (Return Int)

First, let's nail down the core needs: your input strings might use single spaces, tabs, or even consecutive whitespace (a common quirk in exports). The function should ignore extra separators and return a clean column count as an integer.

Key Approach

The critical step is splitting the input on any sequence of whitespace (spaces, tabs, newlines) while filtering out empty strings that come from consecutive separators. This ensures things like "1 3\t4" (two spaces + a tab) get counted as 3 columns, not 4.

Example Implementations

Python

Python's built-in split() method (no arguments) does exactly what we need—it splits on any whitespace and skips empty strings automatically:

def count_columns(text: str) -> int:
    # Split on any whitespace, return the length of the resulting list
    return len(text.split())

Test it with your sample data:

sample_input = "1 3 4 5 2 4 5 2 3 5 7 8 2 5 7 8"
print(count_columns(sample_input))  # Output: 16

# Test mixed spaces/tabs
mixed_input = "1\t3  4\t5 2"
print(count_columns(mixed_input))  # Output: 5

# Test empty/whitespace-only input
empty_input = "   \t  "
print(count_columns(empty_input))  # Output: 0

JavaScript

Use a regex to split on one or more whitespace characters, then filter out any leftover empty strings:

function countColumns(text) {
    const columns = text.split(/\s+/).filter(col => col.trim() !== '');
    return columns.length;
}

Java

Use a regex for whitespace sequences, and handle edge cases where the input is all whitespace:

public static int countColumns(String text) {
    String trimmedText = text.trim();
    // If input is all whitespace, return 0
    if (trimmedText.isEmpty()) {
        return 0;
    }
    // Split on one or more whitespace characters
    String[] columns = trimmedText.split("\\s+");
    return columns.length;
}

Edge Cases Covered

  • Consecutive spaces/tabs (treated as a single separator)
  • Leading/trailing whitespace (ignored)
  • Empty or whitespace-only lines (returns 0 instead of 1)

内容的提问来源于stack exchange,提问作者Riccardo Farina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:56:49