如何按顺序统计字符串中字符?2D平台游戏编辑器字符串压缩方案
Great question—this is a common pattern for compressing tile-based level data, and the core logic is straightforward once you break it down. Let's walk through how to get from your input string to the compressed x4a2x1a54 result, plus the general method for counting consecutive characters.
Step 1: Extract the Pure Tile Sequence
Your input string alternates between tile characters (x for blocks, a for empty space) and a 1 marker (I assume this denotes a single instance of the tile). First, we need to strip out the 1s to get a clean sequence of just tiles. For your example:
- Original string:
x1x1x1x1a1a1x1a1...a1 - Clean tile sequence:
xxxxaaxaaaaa...aaaa(4xs, 2as, 1x, 54as)
Step 2: Count Consecutive Identical Tiles
With the clean sequence in hand, we'll iterate through it while tracking two things: the tile we're currently counting, and how many times it's appeared in a row. Here's a simple pseudocode breakdown of the logic:
# Initialize variables compressed_result = "" if tile_sequence is empty, return "" current_tile = tile_sequence[0] current_count = 1 # Loop through the rest of the tiles for tile in tile_sequence[1:]: if tile == current_tile: current_count += 1 else: compressed_result += f"{current_tile}{current_count}" current_tile = tile current_count = 1 # Add the final group (the loop ends before processing this!) compressed_result += f"{current_tile}{current_count}"
Step 3: Working Code Example (Python)
Since you're building a game editor, here's a Python snippet that implements this logic for your specific input:
# Your original level string level_string = "x1x1x1x1a1a1x1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1" # Extract just the x/a tiles (skip every second character, which are all '1's) tile_sequence = [level_string[i] for i in range(0, len(level_string), 2)] compressed = [] if tile_sequence: current_tile = tile_sequence[0] count = 1 for tile in tile_sequence[1:]: if tile == current_tile: count += 1 else: compressed.append(f"{current_tile}{count}") current_tile = tile count = 1 # Don't forget the final set of tiles compressed.append(f"{current_tile}{count}") # Combine into the final compressed string final_compressed = ''.join(compressed) print(final_compressed) # Output: x4a2x1a54
General Method for Counting Consecutive Characters
This logic works for any string where you need to group consecutive identical characters. The key steps are universal:
- Initialize tracking variables: Start with the first character and a count of 1.
- Iterate and compare: For each subsequent character, if it matches the current one, increment the count. If not, save the current group and reset the tracker.
- Finalize the last group: The loop will exit before processing the final consecutive sequence, so make sure to add it explicitly.
内容的提问来源于stack exchange,提问作者Ryan Sangha

