フィルターのクリア

Search and replace a word of text file from GUI

2 ビュー (過去 30 日間)
Saeed Soltani
Saeed Soltani 2016 年 2 月 29 日
コメント済み: Saeed Soltani 2016 年 3 月 3 日
I need to parse a text file in way like what find and replace (strrep) function does in the string. It actually has to get a word (‘new’) as input from the GUI, search within the text file for a special word (‘old’) and replace it.
Any help would be greatly appreciated

採用された回答

Stephen23
Stephen23 2016 年 2 月 29 日
編集済み: Stephen23 2016 年 2 月 29 日
A text file is a string. So just read the file using fileread, and perform your operations on it:
str = fileread(filename);
str = strrep(str,old,new);
  7 件のコメント
Stephen23
Stephen23 2016 年 3 月 3 日
編集済み: Stephen23 2016 年 3 月 3 日
Reading the inputdlg documentation we find that the output is a cell array. strrep also accepts cell arrays of strings, and then returns a cell array. Oops, providing a cell array to fprintf results in this error message:
Error using fprintf
Function is not defined for 'cell' inputs.
Error in bj (line 9)
fprintf(fid,'%s',str);
By the point this error occurs the file has already been opened for writing (and the contents deleted). To solve this we just need to get the string out of the cell array, using cell array indexing:
str = strrep(str,'old',new{1});
Saeed Soltani
Saeed Soltani 2016 年 3 月 3 日
Thanks a lot Stephen, that was great help :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by