Reputation: 75
I need help solving this problem as I have no idea how to solve this
Define a procedure pick that takes a non-empty string s and a non-negative integer i, and returns a substring of length one consisting of the character at index i in s. Assume that i is a legal index for the string s.
~ (pick "cat" 0)
"c"
~ (pick "cat" 1)
"a"
~ (pick "cat" 2)
"t"
Upvotes: 0
Views: 1124
Reputation: 31147
One solution is to use substring
.
> (substring "Scheme" 1 3)
"ch"
Here the letters of the word "Scheme" are numbered.
The expression (substring "Scheme" 1 3)
makes a new string with
the letters numbered from 1 to 2. The index 3 is the first index
not in the new string.
Since you want to pick out just one character, try this:
> (substring "Scheme" 1 2)
"c"
> (substring "Scheme" 2 3)
"h"
Now you can define your own function:
(define (pick a-string i)
(substring a-string ??? ???))
What should the ??? be?
Upvotes: 1
Reputation: 236004
Try this, it's simple using standard Scheme procedures:
(define (pick str idx)
(string (string-ref str idx)))
Here's how it works: string-ref
returns a character from the string at the given index, and the string
procedure turns the character into a string of length one.
There's no real need to use the substring
procedure (because we only need a single character), but that's a valid alternative, too.
Upvotes: 1