OC--Foundation之NSString

小知识: NS:NextStep   CG:CoreGraphics  

           NSString:不可变字符串    NSMutableString:可变字符串

    URL本地文件头: file://   URL网络文件头:http://

int main(int argc, const char * argv[]){

  int age = 10;

  1.字符串的创建

  NSString *s1 = @"As god name";

  NSString *s2 = [[NSString alloc] initWithString:@"欢迎学习OC"];   // 不常用

  NSString *s3 = [[NSString alloc] initWithFormat:@"欢迎学习OC, age = %d", age];   // 不常用

  NSString  *s4 = [NSString stringWithFormat:@"欢迎学习OC, age = %d", age];

  // C字符串 --> OC字符串

  NSString *s5 = [[NSString alloc] initWithFormat:@"欢迎学习OC"];

  // OC字符串 --> C字符串

  const char *s5 = [s4 UTF8String];

  // 从文件中读取字符串

  NSString *s6 = [NSString stringWithContentsOfFile:@"/Users/apple/Desktop/one.txt" encoding:NSUTF8StringEncoding error:nil];

  // URL字符串的读取

  NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/one.txt"];   // URL路径的创建  

  NSURL *url2 = [NSURL fileURLWithPath:@"/Users/apple/Desktop/one.txt"];   // URL路径的创建

  // 从URL路径中读取字符串

  NSString *s7 = [[NSString alloc] initWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];

  NSLog(@"%@", s7);

    // 将字符串写入到文件中

  NSString *s8 = @"欢迎学习OC";

  NSURL *url3 = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/three.txt"];

  [s8 writeToFile:url3 atomically:YES encoding:NSUTF8StringEncoding error:nil];

  // NSMutableString

   NSMutableString *s10 = [NSMutableString stringWithFormat:@"欢迎学习OC"];

     [s10 appendString:@" 欢迎学习ios开发"];     // 拼接内容到s1的后面

  NSString *s11 = [NSString stringWithFormat:@"欢迎来到我的博客"];

  NSString *s12 = [s2 stringByAppendString:@" and other..."];    // 在s11后添加字符串

 

  // 获取字符串长度
  NSUInteger length = str.length
  // 获取字符串某个位置的字符
  unichar c = [str characterAtIndex:1];

  return 0;

}

 

你可能感兴趣的:(NSString)