Skip to content

字符串反转

字符串反转

示例

输入:'abcd'

输出:'dcba'

代码

javascript
// 输入:'abcd'
// 输出:'dcba'

export function stringReverse (str) {
  let res = ''
  for (let i = str.length -1; i > -1; i--) {
    res += str[i]
  }
  return res
}
typescript
// 输入:'abcd'
// 输出:'dcba'

export function stringReverse (str: string): string {
  let res = ''
  for (let i = str.length -1; i > -1; i--) {
    res += str[i]
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { stringReverse } from './typescript.ts'
import { stringReverse as stringReverseJs } from './javascript.js'

test(`'abcd' toEqual 'dcba'`, () => {
  expect(stringReverse('abcd')).toEqual('dcba')
})

test(`'abcd' toEqual 'dcba'`, () => {
  expect(stringReverseJs('abcd')).toEqual('dcba')
})