main:
- //
- // main.m
- // StringDemo
- //
- // Created by 千 on 16/9/22.
- // Copyright © 2016年 kodulf. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- //
- #import "StringText.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // insert code here...
- NSLog(@"Hello, World!");
- StringText *stringText = [[StringText alloc] init];
- [stringText test];
- }
- return 0;
- }
h:
- //
- // StringText.h
- // StringDemo
- //
- // Created by 千 on 16/9/22.
- // Copyright © 2016年 kodulf. All rights reserved.
- //
- #import <Cocoa/Cocoa.h>
- @interface StringText : NSObject
- -(void)test;
- -(void) createString;
- -(void) appendString;
- -(void) seperaterString;
- @end
- //
- // StringText.m
- // StringDemo
- //
- // Created by 千 on 16/9/22.
- // Copyright © 2016年 kodulf. All rights reserved.
- //
- #import "StringText.h"
- @implementation StringText
- - (void)test {
- [self createString];
- [self appendString];
- }
- /**字符串的创建*/
- -(void) createString{
- NSString *string1 = [[NSString alloc] init];
- NSLog(@"string1 %@",string1);
- NSLog(@"string1 %p",string1);
- string1 = @"";
- NSLog(@"string1 %@",string1);
- NSLog(@"string1 %p",string1);
- NSString *string2 = @"Hello World";
- NSLog(@"string2 %@",string2);
- NSLog(@"string2 %p",string2);
- //和java一样,
- NSString *string3 = @"Hello World";
- NSLog(@"string3 %@",string3);
- NSLog(@"string3 %p",string3);
- //如果是c语言的字符的话
- const char *cString = "c Language String";
- NSString *objectCString = [NSString stringWithCString:cString encoding:NSUTF8StringEncoding];//注意这里使用utf8的编码,如果不写默认的应该就是utf8的
- NSLog(@"c语言的字符串输出:%@",objectCString);
- //格式化输出
- NSString *format = @"%@年%@月%@日";
- NSString *fromatedNSString = [NSString stringWithFormat:format,@"1949",@"10",@"1"];
- NSLog(@"格式化输出的结果:%@",fromatedNSString);
- }
- /**字符串的拼接,这里和java不一样java 可以直接使用+来进行拼接*/
- -(void) appendString{
- NSString *string1 = @"www.";
- NSString *string2 = @"baidu.com";
- //字符串的拼接方法1,使用格式化输出的静态方法
- NSString *string3 = [NSString stringWithFormat:@"%@%@",string1,string2];
- NSLog(@"字符串的拼接%@",string3);
- //字符串拼接方法2,使用格式化输出的对象方法
- NSString *string4 = [string3 stringByAppendingFormat:@"%@%@",@"haha",@"hehe"];
- NSLog(@"字符串的拼接%@",string4);
- //字符串拼接方法3,使用
- NSString *string5 = [string4 stringByAppendingString:@" 我是kodulf,我一个梦想,中国足球走向世界"];
- NSLog(@"字符串的拼接%@",string5);
- }
- //字符串的分割
- -(void) seperaterString{
- NSString *string = @"字符串的拼接www.baidu.comhahahehe 我是kodulf,我一个梦想,中国足球走向世界";
- NSArray<NSString *> *components = [string componentsSeparatedByString:@"."];
- NSLog()
- }
- @end
分隔还可以参考: