【问题标题】:Split sentences to words and count the number of characters 'a' in each word将句子拆分为单词并计算每个单词中字符“a”的数量
【发布时间】:2015-06-25 04:11:04
【问题描述】:

我需要输入带有大写字母的句子,然后将句子拆分为单词,并为每个单词计算字符“a”的数量

我做了这个

clear
sentences=input('Write your sentences: ','s');
low=lower(sentences);
disp('Sentences splitted to words: ');
words=regexp(low,' ','split');
for i=1:length(words)
    disp(words(i))
end

现在我不知道如何计算拆分后每个单词中的字符'a',因为这些单词被转换为单元格。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 从文档这里开始:Characters and Strings
  • 标题中无需人为插入标签;理想情况下,标题应该是连贯的句子

标签: matlab


【解决方案1】:

要处理每个单元格,请将cellfunanonymous function 一起使用,以计算'a' 在每个单词中出现的次数:

count = cellfun(@(w) sum(w=='a'), words);

您可以等效地使用循环:

N = numel(words);
count = NaN(1,N); %// preallocate for speed
for n = 1:N
    w = words{n};
    count(n) = sum(w=='a');
end

【讨论】:

  • w=='a' 对于字符串来说通常是一种不好的做法(除非执行一堆输入验证)。 strfind 可能是更好的选择:count = cellfun('length',strfind(words,'a'))
  • 使用== 测试两个字符串的相等性是不好的做法(它们可能有不同的长度),但我认为将字符串与 字符进行比较并不是不好的做法。还是我错过了什么?
猜你喜欢
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多