Schematic: how to find the position of a char in a string

I am trying to find the index of a string where it is equal to a specific character, but I can figure it out. This is what I got so far, but its not working ...

(define getPos 
  (lambda ()
    (define s (apply string-append myList))
    (getPosition pos (string->list s))))

(define getPosition 
  (lambda (position s)
    (if (and (< position (length s)) (equal? (car s) #\space)) 
        ((set! pos (+ pos 1)) (getPosition (cdr s) pos));increment the positon and continue the loop
        pos)));else

(define length
  (lambda (s);the value s must be coverted to a string->list when passed in
    (cond
      ((null? s) 0)
      (else (+ 1 (length (cdr s)))))))

      

+3


source to share


2 answers


The solution is simple: we have to test every char in the list until we run out of elements or find the first occurrence of char, keeping track of where we are.

Your proposed solution looks strange, in the Scheme we try to avoid set!

other operations that mutate data - the way to work, using recursion to traverse a list of characters. Something like this is preferred:

(define (getPosition char-list char pos)
  (cond ((null? char-list) #f)              ; list was empty
        ((char=? char (car char-list)) pos) ; we found it!
        (else (getPosition (cdr char-list) char (add1 pos))))) ; char was not found

      

For 0-based indexes, use it like this: convert the string to a character list and initialize the position to 0

:



(getPosition (string->list "abcde") #\e 0)
=> 4

      

Of course we can do better using existing routines - here's a more idiomatic solution:

(require srfi/1) ; required for using the `list-index` procedure

(define (getPosition string char)
  (list-index (curry char=? char) 
              (string->list string)))

(getPosition "abcde" #\e)
=> 4

      

+2


source


Solution with for

:

#lang racket

(define (find-char c s)
  (for/first ([x s]              ; for each character in the string c
              [i (in-naturals)]  ; counts 0, 1, 2, ...
              #:when (char=? c x))
    i))

(find-char #\o "hello world")
(find-char #\x "hello world")

      



Output:

4
#f

      

0


source







All Articles