位数不足补0
NSString *str = [NSString stringWithFormat:@"%02zd点",n];
// e.g: %02zd -->05 %03zd-->005
获取汉字拼音
- (NSString *) pinyinFirstLetter:(NSString*)sourceString {
NSMutableString *source = [sourceString mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO); // 这一行是去声调的
NSLog(@".....>> %@",source);
return source;
}
首字母大写
NSString *str = @"abcdefghijklmn";
NSString *resultStr;
if (str && str.length > 0) {
resultStr = [str stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[str substringToIndex:1] capitalizedString]];
}
NSLog(@"%@", resultStr);
字符串开头、结尾
if([str hasPrefix:@"http"]){
}
if([str hasSuffix:@".com"]){
}
长按复制
[self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];
}
- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = @"需要复制的文本";
}
判断String是否包含某字符串
[str containsString:@"abc"];
或
NSString *women = @"Hey you are boy?";
if ([women containsString:@"boy"])
/*--->字符串开头 是否含有某字符串
if ([string hasPrefix:@"hello"]) {
/*--->字符串末尾 是否有某字符串
if ([string hasSuffix:@"bitch"]) {
取单个字符
// 取第i个字符
NSString *chara = [string substringWithRange:NSMakeRange(i, 1)];
字符串反转
- (NSString *)reverseWordsInString:(NSString *)str
{
NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
for (NSInteger i = str.length - 1; i >= 0 ; i --)
{
unichar ch = [str characterAtIndex:i];
[newString appendFormat:@"%c", ch];
}
return newString;
}
或
- (NSString*)reverseWordsInString:(NSString*)str
{
NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reverString appendString:substring];
}];
return reverString;
}
判断字符串是否为空
+ (BOOL)isEqualToNil:(NSString *)str {
return str.length <= 0 || [str isEqualToString:@""] || !str;
}
- (BOOL)isExist {
NSString *str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return (str.length != 0);
}
或
使用宏定义:
#define Validity_Str(string) (((string != nil) && (string.length>0))?YES:NO) // 判断字符串是否有效
在文字中添加表情
//emoji 表情,只需在label的text中加上“\u+表情代码”即可。如:
aLabel.text = @"今天天气非常好\uE337";
附:表情代码大全(取Unicode编码的代码,如:U+1F604-->U0001F604)
http://punchdrunker.github.io/iOSEmoji/table_html/index.html
判断输入的 是否汉字
- (BOOL)isHasChineseWithStr:(NSString *)strFrom {
for (int i=0; i
分隔字符串,分隔成n个元素的数组
NSString*string =@"sdfsfsfs-dfsdf";
NSArray *array = [string componentsSeparatedByString:@"-"];
NSLog(@"array:%@",array);
//结果是adfsfsfs和dfsdf
汉字编码
NSstring *str = [chineseName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
去掉HTML标签
-(NSString *)filterHTML:(NSString *)html
{
NSScanner * scanner = [NSScanner scannerWithString:html];
NSString * text = nil;
while([scanner isAtEnd]==NO)
{
[scanner scanUpToString:@"<" intoString:nil];
[scanner scanUpToString:@">" intoString:&text];
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
}
return html;
}
动态计算字串宽度、高度
// 动态计算文本宽度
+ (CGFloat)widthWithText:(NSString *)text andFontSize:(CGFloat)fontSize{
CGRect rect =
[text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}
context:nil];
return rect.size.width;
}
// 动态计算文本高度
+ (CGFloat)heightWithText:(NSString *)text andFontSize:(CGFloat)fontSize{
CGRect rect =
[text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 100, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}
context:nil];
return rect.size.height;
}
计算字符串字符长度,一个汉字算两个字符
-(NSUInteger) unicodeLengthOfString: (NSString *) text
{
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i < text.length; i++)
{
unichar uc = [text characterAtIndex: i];
asciiLength += isascii(uc) ? 1 : 2;
}
return asciiLength;
}
字符串base64编码
+ (NSString *)base64StringFromText:(NSString *)text {
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [data base64EncodedStringWithOptions:0];
return base64String;
}
/* 解码 */
+ (NSString *)textFromBase64String:(NSString *)base64 {
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return text;
}
字符串解码
NSString *result = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
对字符串进行UTF-8编码:输出UTF-8格式
[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
字符串编码
NSString *urll = self.URL;
urll = [urll stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"%<>[\\]^`{|}\"]+"].invertedSet];
// 我们一般用这个方法处理stringByAddingPercentEscapesUsingEncoding但是这个方法好想不会处理/和&这种特殊符号,这种情况就需要用下边这个方法处理
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
字典转字符串
SData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err)
{
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
模型数组转json字符串
//先模型数组 转 字典数组
NSArray *dictArray = [PDcycleImageItem mj_keyValuesArrayWithObjectArray:_extraCycleImgArray];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictArray options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
字符串替换
NSString*str =@"12345678";
NSString*Str2 = [str stringByReplacingOccurrencesOfString:@"345"withString:@"543"];
去除所有的空格、换行
+ (NSString *)removeSpaceAndNewline:(NSString *)str {
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
字符串拼接相关
1. 如果count不足2位 用0在最前面补全(2代表总输出的个数)
NSInteger count = 5;
NSString *string = [NSString stringWithFormat:@"%02zd",count];
//输出结果是: 05
2. 加百分号%
NSInteger count = 50;
//%是一个特殊符号 如果在NSString中用到%需要如下写法
NSString *string = [NSString stringWithFormat:@"%zd%%",count];
//输出结果是: 50%
3. 含双引号:如果在NSString中用到"需要用\进行转义
NSInteger count = 50;
NSString *string = [NSString stringWithFormat:@"%zd\"",count];
//输出结果是: 50"
获取字符串中的数字
NSString *ssstr = @"额发发哦342.5范文芳个人房贷";
NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
float num =[[ssstr stringByTrimmingCharactersInSet:nonDigits] floatValue];
NSLog(@" num %.1f ",num);
截取某个字符串之后的字符串
NSRange range = [aString rangeOfString:@"redirect="]; //现获取要截取的字符串位置
NSString *rurl = [aString substringFromIndex:range.location]; //截取字符串
//--返回结果包含该字符串 :redirect=
截取两个指定字符串中间的 字符串
NSString *string = @"这是要截取的内容";
NSRange startRange = [string rangeOfString:@"\">"];
NSRange endRange = [string rangeOfString:@""];
NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
NSString *result = [string substringWithRange:range];
NSLog(@"%@",result);
获取字符串中的URL
正则表达式 的应用
+ (NSArray *)getURLFromString:(NSString *)string {
NSError *error;
//可以识别url的正则表达式
NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
NSMutableArray *arr=[[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in arrayOfAllMatches){
NSString* substringForMatch;
substringForMatch = [string substringWithRange:match.range];
[arr addObject:substringForMatch];
}
return arr;
}
截取指定范围的子串
NSString *str = @"今天天气真不错,是风和日丽的,我们下午没有课,是心情也不错";
// 从x位置开始,到最后结束,包括x
NSString *str1 = [str substringFromIndex:17];
//从开始位置到指定位置x,不包括x
NSString *str2 = [str substringToIndex:7];
// 某个范围内
NSRange range = {7, 10};
NSString *str3 = [str substringWithRange:range];
NSRange range1 = [str rangeOfString:@"我们下午没有课"];
NSString *str4 = [str substringFromIndex:range1.location];
//从某个字串的位置开始,到结尾
NSUInteger loc1 = [str rangeOfString:@"/"].location + 1 ;
NSString *result = [str substringFromIndex:loc1];
设置label富文本
// 创建Attributed
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:_label.text];
// 改变的区间
NSUInteger firstLoc = [[noteStr string] rangeOfString:@"金"].location + 1;
NSUInteger secondLoc = [[noteStr string] rangeOfString:@"元"].location;
NSRange range = NSMakeRange(firstLoc, secondLoc - firstLoc);
// 改变颜色
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range];
// 改变字体大小及类型
[noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-BoldOblique" size:27] range:range];
[_label setAttributedText:noteStr]; // 为label添加富文本 属性
文字中添加图片
//先实例化一个Lable
... ...
// 创建一个富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"超时罚款24元/小时"];
// 创建NSTextAttachment对象,用来装图片
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
attch.image = [UIImage imageNamed:@"parking_caveat_normal"];
attch.bounds = CGRectMake(0, 0, 15, 15);
// 创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
// 在文字后面添加图片
[attri appendAttributedString:string];
或
// 在文字下标第几个添加图片
[attri insertAttributedString:string atIndex:0]; //0就是文字前添加图片
// 用label的attributedText属性来使用富文本
lable.attributedText = attri;
持续更新中... ...