1
$\begingroup$

I want to find the position of letter i in each word of a text. Take their positions and then sum them up. Example, in simplicity, the score will be 2+6+8=16. In this way, I calculate the score for all words and then sum the scores.

I wrote the following codes till now, but unable to combine them.

Data = "Simplicity and Importance are classic and ironic"
TextWords[Data]
Transpose[StringPosition[ToString[Data], "I"]][[1]]
Transpose[StringPosition[ToString[Data], "i"]][[1]]

Please help

$\endgroup$
  • 1
    $\begingroup$ Maybe start with Position[Characters[Data], "i" | "I"] ? $\endgroup$ – b.gates.you.know.what Feb 27 at 10:20
2
$\begingroup$

Transpose[StringPosition[Data, "i", IgnoreCase -> True]][[1]]

$\endgroup$
0
$\begingroup$

You may use StringPosition and StringSplit for this, e.g.

score[string_] := Total[
  (First /@ StringPosition[#, "i"])& /@ StringSplit[string],
  Infinity
]

defines a score function that does what you asked for. For example:

score["Simplicity"]
(* 16 *)

score["Simplicity and Importance are classic and ironic"]
(* 28 *)

You may use ToLowerCase if you wish to count capital "I" as well.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.