zoukankan      html  css  js  c++  java
  • Foundation框架系列-NSString

    NSString

    OC字符串与C语言字符串转换

    NSString *str = @"Hello world ! !";
    // OC字符串 --> C语言字符串
    char *c = [str UTF8String];
    
    // C字符串 --> OC语言字符串
    char *c = "Hello world ! !";
    NSString *str = [[NSString alloc] initWithUTF8String:c];
    

    从文件中读取字符串

    // 文件的绝对路径
    NSString *str1 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/abc.txt" encoding:NSUTF8StringEncoding error:nil];
        
    // 资源
    NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/abc.txt"];
    NSString *str2 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    

    获取字符串中指定内容的NSRange

    NSString *str = @"Hello world";
    // 获取字符串
    NSRange range = [str rangeOfString:@"Hello"];
    

    字符串的截取

    NSString *str = @"HelloWorld";
    
    // 指定index开始截取字符串(包含index)
    NSString *str2 = [str substringFromIndex:2];
    
    // 从字符串开始位置开始截取到index(不包含index)
    NSString *str2 = [str substringToIndex:3];
    
    // 从index开始包含index截取长度为length的字符串
    NSString *str2 = [str substringWithRange:NSMakeRange(2, 2)];
    
    // 从字符串中截取已知字符后面的全部内容
    NSString *str = @"wechat://router";
    NSRange chemeRange = [str rangeOfString: @"wechat://"];
    NSString *str2 = [str substringFromIndex:chemeRange.location + chemeRange.length];
    NSLog(@"
    str2 = %@", str2); // 输出结果: router
    
  • 相关阅读:
    系统开机自动运行程序和自动启动服务
    Show/hide mouse cursor
    Trap mouse events outside of my application
    Delphi防止同时出现多个应用程序实例CreateMutex
    用Delphi实现抓屏
    .NET四种注释规范
    再谈C#里4个访问权限修饰符
    什么是组件以及为什么使用组件
    做项目的时候千万不能懒!
    范式篇之一范式理论
  • 原文地址:https://www.cnblogs.com/CoderHong/p/9062318.html
Copyright © 2011-2022 走看看