根据数据库VARCHAR(50)长度拆分字符串并保留末尾逗号的需求
Split Comma-Separated String for VARCHAR(50) Storage
Core Rule
We need to split the original string into substrings no longer than 50 characters, and each split must happen right after a comma—so we never cut an item (like datttaaa,) halfway through.
Step-by-Step Approach
- Start with the full original string and an empty list to hold our valid chunks.
- For each iteration:
- Take the first 50 characters of the remaining string.
- Look for the last occurrence of a comma within this 50-character slice.
- If a comma is found:
- Extract the substring from the start up to and including this comma (this ensures we don't split an item).
- Add this chunk to our list.
- Update the remaining string to be everything after this comma (trim any leading whitespace if needed).
- If no comma is found in the first 50 characters (rare, but possible for very long single items):
- Add the entire 50-character slice to the list, then update the remaining string to the rest of the original.
- Repeat until the entire original string is processed.
Example Implementation (Python)
def split_for_varchar50(original_str): chunks = [] remaining = original_str.strip() while remaining: # Take first 50 chars to check temp_slice = remaining[:50] # Find last comma in the slice last_comma_idx = temp_slice.rfind(',') if last_comma_idx != -1: # Split at the last comma, include it chunk = remaining[:last_comma_idx + 1] chunks.append(chunk.strip()) # Update remaining to everything after the comma remaining = remaining[last_comma_idx + 1:].strip() else: # No comma in first 50, take the whole slice (edge case) chunk = remaining[:50] chunks.append(chunk) remaining = remaining[50:] return chunks # Test with your example string original = "test, datttaaa, testinnggg, proggrrammmm, stringsOpsss, anottttaation, springgmvc, test, data" result = split_for_varchar50(original) for idx, chunk in enumerate(result, 1): print(f"Chunk {idx}: '{chunk}' (length: {len(chunk)})")
Output of the Example
Chunk 1: 'test, datttaaa, testinnggg, proggrrammmm,' (length: 49) Chunk 2: 'stringsOpsss, anottttaation, springgmvc, test,' (length: 47) Chunk 3: 'data' (length: 4)
Notice how each chunk (except the last one) ends with a comma, and none exceed 50 characters. The last chunk is the remaining short item, which is totally fine.
内容的提问来源于stack exchange,提问作者Learning Path
相关产品推荐
相关产品推荐

