How to separate characters from words and write both of them to matrice when reading from text file
古いコメントを表示
example I have: ",considering);" I want this like
A{1}{1} = ,
A{1}{2} = considering
A{1}{3} = )
A{1}{4} = ;
note: there is no white space between characters and words
2 件のコメント
per isakson
2014 年 11 月 25 日
I assume that you look for a code that will handle more strings than this example. What is the rule according to which the input string shall be split?
Tural
2014 年 11 月 25 日
回答 (2 件)
Geoff Hayes
2014 年 11 月 25 日
Tural - you could try using regexp to split the string into its letter and non-letter parts, splitting on the non-letters. Something like
str = ',considering);';
[A, nonLetterIdcs] = regexp(str,'[^A-Za-z]','split');
In the above, we split the str message on those characters that are not (the ^ means "not") in the square bracket expression (so we split on anything that is not in the range A-Z or a-z), and our output becomes
A =
'' 'considering' '' ''
nonLetterIdcs =
1 13 14
A is a cell array, and nonLetterIdcs is an array of indices of the non-letters that we have split on. Now we need to combine the two as
A(cellfun(@(x)isempty(x),A)) = cellstr(str(nonLetterIdcs)');
We use cellfun to look for the empty strings of A which correspond to the positions in the original str that have non-letters. And we need to "fill" these empty strings with the corresponding non-letter from str, using the nonLetterIdcs. Having done that, A becomes
A =
',' 'considering' ')' ';'
per isakson
2014 年 12 月 23 日
A construct based on regexp:
>> A{1} = regexp( ',considering);', '\W|\w++', 'match' );
>> A{1}{2}
ans =
considering
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!