如何在MATLAB中按$分割.txt文件内容并实现换行?
Hey there! Let's work through this MATLAB text formatting problem together. You want to take a text file with $ separators, split the content at each $, and format it with line breaks (plus replace $ with spaces based on your example output). Here are a few simple, effective approaches:
Method 1: Quick Replace & Write (Great for Simple Cases)
If you just need to swap every $ for a space followed by a line break (or just a line break), this one-liner-style approach works perfectly:
% Read the entire content of your input file in one go input_content = fileread('your_input_file.txt'); % Replace each '$' with a space + newline (change to '\n' if you don't want the space) processed_content = strrep(input_content, '$', ' \n'); % Write the cleaned content to a new output file fid = fopen('formatted_output.txt', 'w'); fprintf(fid, '%s', processed_content); fclose(fid);
For your sample input hello$world good$morning thank$you$everybody, this will produce:
hello world good morning thank you everybody
Method 2: Phrase-by-Phrase Formatting (Matches Your Example)
Your desired output shows full phrases like hello world on separate lines. This approach splits the original text by spaces first, cleans up the $ in each phrase, then writes each phrase to its own line:
% Grab all text from the input file input_text = fileread('your_input_file.txt'); % Split the text into individual phrases using spaces as the separator phrases = split(input_text, ' '); % Replace every '$' with a space in each phrase cleaned_phrases = strrep(phrases, '$', ' '); % Write each cleaned phrase to the output file, one per line fid = fopen('final_output.txt', 'w'); for idx = 1:length(cleaned_phrases) fprintf(fid, '%s\n', cleaned_phrases{idx}); end fclose(fid);
This will give you exactly the output you showed:
hello world good morning thank you everybody
Bonus: Line-by-Line Processing (For Large Files)
You mentioned thinking about fgetl and ischar—if you're working with a huge file that can't fit in memory, reading line by line is the way to go. Here's how to use those functions:
% Open your input and output files input_fid = fopen('your_input_file.txt', 'r'); output_fid = fopen('line_by_line_output.txt', 'w'); % Read lines one at a time until we hit the end of the file current_line = fgetl(input_fid); while ischar(current_line) % ischar checks if we're still reading valid text (not EOF) % Replace '$' with space + newline (adjust as needed) processed_line = strrep(current_line, '$', ' \n'); fprintf(output_fid, '%s\n', processed_line); current_line = fgetl(input_fid); end % Don't forget to close both files! fclose(input_fid); fclose(output_fid);
ischar here just helps us confirm that fgetl returned a valid line of text (instead of -1, which means we've reached the end of the file).
内容的提问来源于stack exchange,提问作者T.Ghosh

