Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

iphone - string replace phone number iOS swift

I import a phone-number from "Contacts" and save in NSString. this string contains white-space and I try to delete them using the method:

numero = numero.stringByReplacingOccurrencesOfString(" ", withString: "")

this method doesn't work.


func sostituisci( stringa: NSString! ) -> NSString     
{         
var numero: NSString = ""         
NSLog(stringa) 
numero = ((stringa as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString) 
NSLog(numero)

return numero
}

the output unchanged


log

2014-11-05 17:54:50.734 HappyRicarica[33438:3119446] (327)?124-3503
2014-11-05 17:54:50.737 HappyRicarica[33438:3119446] (327)?124-3503
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect that the space character in your string is not really a space. Try adding this after NSLog(string) to see what the unicode scalar values are for the characters in your string:

for uni in (stringa as String).unicodeScalars {
    println("(uni) = (uni.value)")
}

The expected output for "(327) 124-3503" is:

( = 40
3 = 51
2 = 50
7 = 55
) = 41
  = 32
1 = 49
2 = 50
4 = 52
- = 45
3 = 51
5 = 53
0 = 48
3 = 51

From your comment, your space has value 160 instead of 32. You could remove that with:

numero = stringa.stringByReplacingOccurrencesOfString(String(Character(UnicodeScalar(160))), withString: "")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...