StringAPP
1.字符串直接赋值;
NSString *str1 = @"xxxx";
str1 = [NSString stringWithUTF8String:"xxx"];类方法;
str1 = [NSString stringWithFormat:@“xxx"];
2.写文件,如果文件之前被创建,这内容将被替换,没有创建则从新创建;
st1=@"xxx";
[st1 writeToFile:path atomically:YES encoding:协议 error: ];
3.将文本文件内容读取到字符串对象中,并将首地址保存到str1里
st1=[NSString stringWithContentsOfFile:PATH encoding:协议 error: ];一般协议为NSUTF8StringEncoding,error返回为nil;
4.格式化字符;
int day=1;
st1=[NSString stringWithFormat:@"今天星期%d",day];
5.比较字符串大小;
NSComparisonResult res=[@"xxx" compare:@“xxx"];
6检测网页前缀;
NSString *path=@"www.baidu.com";
if (![path hasPrefix:@"http://"]) {
path=[NSString stringWithFormat:@"http://%@",path];
}
7检验后缀;
NSString *filename=@"test";
if (![filename hasSuffix:@".txt"]) {
filename=[NSString stringWithFormat:@"%@.txt",filename];
}
8.连接字符串;
st1=[st1 stringByAppendingString:@"xxx"];
9直接加后缀;
NSString *desk=path;
st1=[desk stringByAppendingFormat:@".txt"];
10.直接加后缀,且前面自带分隔符;
st1=[desk stringByAppendingPathComponent:@".txt"];
11.加扩展名,且自带.;
st1=[desk stringByAppendingPathExtension:@"exe"];
12.打印最后的文件名;
NSArray *array=[st1 pathComponents];
13.删除扩展名;
filename=[array lastObject];
filename=[filename stringByDeletingPathExtension];
14.分割成字符的集合,当字符间分割符一样时。;
NSString *Value=@"1;2.3";
array=[Value componentsSeparatedByString:@"."];
15.分割成字符的集合,分割符不样时;
NSCharacterSet *set=[NSCharacterSet characterSetWithCharactersInString:@" . ;"];
array=[Value componentsSeparatedByCharactersInSet:set];
16.打印字符个数;
NSString *st2=@"hello gilr hello word";
NSLog(@"字符个数:%lu",st2.length);
打印字符长度;
NSLog(@"字符串长度:%lu",[st2 lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
17.将字符扩充到指定的个数,扩充的字符可指定从哪位开始添加,如果原本的字符超过指定的个数将删除;
st2=[st2 stringByPaddingToLength:30 withString:@"lipiao" startingAtIndex:0];
18.用hi来替换hello;
st2=[st2 stringByReplacingOccurrencesOfString:@"hello" withString:@"hi"];
选择段来替换,从第0个字符到第4个有hi来替换;
NSString *st3=@"abcdefg";
NSRange range1=NSMakeRange(0, 4);
st3=[st3 stringByReplacingCharactersInRange:range1 withString:@"hi"];
用word来替换hi;
st3=[st3 stringByReplacingOccurrencesOfString:@"hi" withString:@"word" options:1 range:range1];
19.删除首尾空白字符;
NSString *st4=@" abc abc ";
st4=[st4 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
从两头找字符,有跟字符集里面一样的删除,空格也算,遇到不是则停止删除;
st4=[st4 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" bc "];
20.获取从x开始的字符 substringFromIndex:x ;
获取从0到x的字符 substringToIndex:x;
获取一个范围内的字符串;
NSRange range=NSMakeRange( 0,8);
st4=[st4 substringWithRange:range];
21大写,小写,首字母大写;uppercaseString;lowercaseString;capitalizedString;
22.打开网页;
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSString *content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",content);
[content writeToFile:@"/Users/apple/desktop/test.html" atomically:YES encoding:NSUTF8StringEncoding error:nil];
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。