【问题标题】:MatLab equivalent of charAt() in javaMatLab 等价于 java 中的 charAt()
【发布时间】:2013-12-11 05:40:30
【问题描述】:

我是 MatLab 的初学者,但我在 java 方面有很多经验。我正在循环一个字符串,但我需要能够从java中执行一个简单的方法,比如charAt()。我查看了堆栈溢出并尝试搜索任何等效方法,但我一直没有解决方案。有什么想法吗?

【问题讨论】:

标签: java matlab


【解决方案1】:

字符串只是 Matlab 中的数组。这样您就可以轻松创建自己的简单charAt 函数:

str = 'somestring';
charAt = @(str,idx)str(idx);

那么charAt(str,5)会返回s(这个简单的函数不输入验证)。但是,直接索引到字符串通常更容易:str(5)

请注意,Java 的 charAt 使用从零开始的索引,而 Matlab 对所有内容都是从一开始的。您可以使用idx+1 来模拟Java 版本。

【讨论】:

    【解决方案2】:

    如果你正在循环一个现有的字符串,它会是这样的:

    mystring = 'example'; % The string
    for ind = 1:length(mystring) % For loop from beginning to end of string
        current_char = mystring(ind); % Character at the current index of the string
        fprintf(current_char); % Prints the character to screen
    end
    

    在这种情况下,for 循环完成后的最终打印输出将显示为 example

    在 Matlab 中,字符串向量被视为与任何其他向量一样,您可以使用 v(ind) 访问向量 v 的元素,其中 ind 是您要访问的元素的索引。这就是current_char = mystring(ind) 行中正在发生的事情。阅读本文以获取更多信息:http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

    【讨论】:

    • 我收到一个错误:Warning: string is obsolete and will be discontinued. Use char instead.
    • 对不起,我的代码最初有一个错误(用“string”而不是“mystring”)。我在编辑中更正了它。
    【解决方案3】:

    如果需要,您可以在 matlab 中使用来自 java 的 charAt

    str = 'somestring';
    strJava = java.lang.String(str); % convert to java string
    strJava.charAt(5) 
    ans =
    
    t
    

    【讨论】:

    • 谢谢,但它必须是 Matlab
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2012-10-18
    • 2022-11-02
    • 2014-09-07
    相关资源
    最近更新 更多