Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Finding Characters place in a string by number of characters

1 回表示 (過去 30 日間)
Aaronyar
Aaronyar 2017 年 9 月 6 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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?

回答 (1 件)

John Chilleri
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!

この質問は閉じられています。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by