2017-06-16 59 views
0

好吧,我已经从文本文件中检索到了这个字符串,现在我应该将它移动一个指定的数量。因此,例如,如果我检索到的字符串是在matlab中移动一个字符串

生存还是毁灭
这是一个问题

和移位数为5,则输出应该是

stionTo是或不是
到beThat是阙

我打算使用circshift,但给定的字符串不会有匹配的维数。此外,我会检索的字符串将来自.txt文件。

因此,这里是我用

S = sprintf('To be, or not to be\nThat is the question') 

circshift(S,5,2) 

的代码,但输出是

stionTo是,或不被
这是阙

,但我需要

stionTo是,或不是
到beThat是阙

+1

这个字符串是如何存储的?它是一个String对象吗?它是一个带有换行符的char数组吗?它是char数组的单元数组吗?你有什么尝试?你能告诉我们你的代码吗? – beaker

+0

你到底做了什么? 'circshift(S,5,2)'对我来说工作得很好,其中'S = sprintf('是或不是\ n那就是问题')' –

+0

不会每次都会有不同的字符串,所以我不会知道circshift是否每次都提供该输出。 – JaZZyCooL

回答

1

通过存储新线的位置,除去新生产线,并在以后,我们可以做到这一点增加他们回来。此代码确实依赖于仅在MATLAB 2016b及更高版本中可用的insertAfter函数。

S = sprintf('To be, or not to be\nThat is the \n question'); 
newline = regexp(S,'\n'); 
S(newline) = ''; 
S = circshift(S,5,2); 
for ii = 1:numel(newline) 
    S = insertAfter(S,newline(ii)-numel(newline)+ii,'\n'); 
end 
S = sprintf(S); 
1

您可以通过对非换行符的索引执行循环移位来完成此操作。 (实际上下面的代码跳过与ASCII码的所有控制字符< 32)

function T = strshift(S, k) 
    T = S; 
    c = find(S >= ' '); % shift only printable characters (ascii code >= 32) 
    T(c) = T(circshift(c, k, 2)); 
end 

采样运行:

>> S = sprintf('To be, or not to be\nThat is the question') 

S = To be, or not to be 
That is the question 

>> r = strshift(S, 5) 

r = stionTo be, or not 
to beThat is the que 

如果你想跳过的换行符,只是改变

c = find(S != 10); 
相关问题