Info
此问题已关闭。 请重新打开它进行编辑或回答。
Finding Characters place in a string by number of characters
1 次查看(过去 30 天)
显示 更早的评论
I am editing a text file for that I'm reading the text file in to a string cell array.
I want to change the strings on a specific line by the place of the characters. for example the line is like this:
1 4 23 0.05 0.125 574
and I want to change the column number 16 to 25 in this line which contains "23". for a purpose of using in another software it should be exactly columns 16 to 25. how can address it in my code? or how can I specify the columns 16 and 25 in my code?
0 个评论
回答(1 个)
John Chilleri
2017-9-6
Hello,
You should be able to modify only columns 16 to 25 of that specific line with the following,
fd = fopen('yourfile'); % open file
yourtext = textscan(fd,'%s','Delimiter','\n'); % read lines into cell array
yourtext = yourtext{1}; % fix cell array to be nx1 rather than a 1x1 containing the nx1
yourtext{line} = [yourtext{line}(1:15) 'this will replace 16 to 25' yourtext{line}(26:end)]; % change line
fclose(fd); % close file
You can do this in many ways, such as by finding the line with regexp, but the above is fine if you know the line number.
Also, if you want to write the edited file back to the file,
fd = fopen('yourfile','w'); % open and clear content from file
fprintf(fd,'%s\n',yourtext{:}); % write strings in yourtext to file
fclose(fd); % close file
This will delete the contents of the file and replace them with the strings in yourtext, which should produce the same file with the edited text (wouldn't hurt to save a backup).
Hope this helps!
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!