[TIL] Swift - String 관련 함수

신승현·2024년 2월 8일

TIL

목록 보기
19/72

1. String.Index

  • String.Index는 Swift에서 문자열의 인덱스를 표현하기 위해 사용하는 특수한 타입이다.

2. 문자열의 맨 첫 글자 구하기

  • prefix(n) : 앞에서부터 n글자를 가져올때 사용한다.
    var he = hello.prefix(2);
  • startIndex 활용하기
    var first = hello[hello.startIndex];
  • 0번째 인덱스를 나타내는 인덱스 생성
    String.Index(encodedOffset: 0);

3. 문자열의 두 번째 글자 구하기

  • secondIndex라는 변수로 두 번째 인덱스를 생성 후, 그 변수로 두 번째 글자를 구한다.
    var secondIndex = hello.index(after: hello.startIndex);
    var second = hello[secondIndex];

4. 문자열의 n번째 글자 구하기

  • n번째 글자 구하기의 경우 아래와 같이 offsetBy를 n으로 설정해 구한다.
    var nIndex = hello.index(hello.startIndex, offsetBy: n);

5. 문자열의 n번째 이후 모든 글자 구하기

  • subfix(n) : 뒤에서부터 n글자 가져오기
    var str1 = s.suffix(2) // lo
  • prefix(n) : 앞에서부터 n글자 가져오기
    var str2 = hello.prefix(3) // hel
profile
개발자

0개의 댓글