MistyD
MistyD

Reputation: 17253

Iterating through a string using For loop

I am trying to iterate through the characters of string using for loop however I get the following error

let str = "Hello"
for var=0 to (String.length str -1) do
  let temp = String.get str var
done;;

Error : Syntax error

I tried this code here

let str = "Hello";;
for i = 0 to (String.length str -1) do
    Printf.printf "%s" String.get str i
done;;

and this is the error i get

Error: This expression has type
         ('a -> 'b -> 'c, out_channel, unit, unit, unit, 'a -> 'b -> 'c)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b -> 'c, out_channel, unit, unit, unit, unit)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b -> 'c is not compatible with type unit 

Upvotes: 0

Views: 2287

Answers (2)

Chris
Chris

Reputation: 36620

let str = "Hello"
for var=0 to (String.length str -1) do
  let temp = String.get str var
done;;

This fails for multiple reasons. The str binding either needs:

  • To be a local binding.
let str = "Hello" in
for var=0 to (String.length str -1) do
  let temp = String.get str var
done;;
  • Or we can use a ;; token to end it as a top-level binding.
let str = "Hello";;
for var=0 to (String.length str -1) do
  let temp = String.get str var
done;;
  • Or we need to make the following a top-level binding so that the parser knows where the binding ends.
let str = "Hello"

let () =
  for var=0 to (String.length str -1) do
    let temp = String.get str var
  done

Your internal binding also doesn't work, because a local binding needs an in. You then need some expression that uses this value. And bear in mind that String.get returns a char rather than string so use the %c format specifier.

let str = "Hello"

let () =
  for var=0 to (String.length str -1) do
    let temp = String.get str var in
    Printf.printf "%c" temp
  done

As for the following, aside from any of the issues above, this suffers from a precedence issue.

let str = "Hello";;
for i = 0 to (String.length str -1) do
    Printf.printf "%s" String.get str i
done;;

Printf.printf "%s" String.get str i parses as: (Printf.printf) ("%s") (String.get) (str) (i).

Clearly you meant for it to parse as below, so simply use those parentheses.

Printf.printf "%c" (String.get str i)

Upvotes: 0

user2983378
user2983378

Reputation:

I guess this will work

#let s = "Hello";;
s : string = "Hello"
#for i = 0 to string_length s - 1 do
    print_char s.[i]; print_string " "
  done;;
o k - : unit = ()

Upvotes: 1

Related Questions