一、字符串操作
1.截取字符串操作
var s="这是取字符串例程"
//取左边的第二字后面的字
var ns1=(s as NSString).substringFromIndex(2)
//从左边开始取5个文字
var ns2=(s as NSString).substringToIndex(5)
//左边第五个字后到文字
var ns3=(s as NSString).substringWithRange(NSMakeRange(5, 1))
2.字符串各类操作
//-----------大写转换
var strA = "Hello"
var strB = strA.uppercaseString
print (strB)
//===========小写转换
var strC = strA.lowercaseString //lowercaseString 字符串转换小写
print(strC)
//取绝对值
abs(-10)
fabs( -10.000)
fabsf( -10.00)
//按位取反
let ini: UInt8 = 0b00001111
let inv = ~ini
String(inv,radix:2)
//按位与
let first: UInt8 = 0b11111100
let last: UInt8 = 0b00111111
let mid = first & last
String(mid,radix:2)
//按位或
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits
//按位异或
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits
二、进制的转换
1.十进制 -> 十六进制
func dec2hex(num:Int) -> String {
return String(format: "%0X", num)
}
2.十六进制 -> 十进制
func hex2dec(num:String) -> Int {
let str = num.uppercaseString
var sum = 0
for i in str.utf8 {
sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
if i >= 65 { // A-Z 从65开始,但有初始值10,所以应该是减去55
sum -= 7
}
}
return sum
}
3.十进制 -> 二进制
func dec2bit(var number:Int) -> String {
var str = ""
while number > 0 {
// 累加二进制的个位
str = "\(number & 1)" + str
// 向左移位去掉个位
number = number >> 1
}
return str
}
##4.二进制 -> 十进制
func bin2dec(var number:Int) -> Int {
var sum = 0
var bit = 1
while number > 0 {
sum = (number % 10) * bit + sum
number /= 10
bit *= 2
}
return sum
}
5.十到十六进制 到八 到二进制
let num = 10
String(num,radix:2)
String(num,radix:8)
let l = String(num,radix:16)
hex2dec(l)