zoukankan      html  css  js  c++  java
  • 删除字符串中指定子串

    1.给定一个字符串,判断字符串中是否含有"png",如果有就删除。

            题外话:在API中,方法名的首单词暗含了该方法的返回值类型,方法名中冒号前的单词暗含了参数类型,通常来说,方法名以动词开头的无返回值,以名词开头的有返回值。如:集合中,NSString,NSArray,NSDictionary等不可变家族在API中方法名均以名词开头,从方法名的首单词可以看出返回值是什么类型的;而NSMutableString,NSMutableArray,NSMutableDictionary等可变家族在API中方法名均以动词开头,无返回值。

    //此题有两种解法

    //方法一

                NSString *string = @"xxx.pngpngpng";

                NSString *result = [string stringByReplacingOccurrencesOfString:@"png" WithString:@""];

                NSLog(@"%@", result);

    //打印结果为: xxx.

           以上是让指针string直接指向常量区的,常量区的内容是不可改变的,这点与NSString本身所具有的特性是一致的,但是如果写成如下形式系统就会出现警告:

    NSMutableString *string1 = @"xxx.pngpngpng";

    //报错信息: Incompatible pointer types initializing 'NSMutableString *' with an expression of type 'NSString *' 

    //用NSString *类型的表达式,即常量表达式给NSMutableString *类型的指针进行初始化,两种类型不匹配。

    //方法二

                NSMutableString *str = [NSMutableString   stringWithFormat:@"xxx.pngpngpng"];

                NSRange substr = [str rangeOfString:@"png"];

                while (substr.location != NSNotFound) {

                      [str deleteCharactersInRange:substr];

                //如果NSRange的范围不进行重新定位,会造成程序因为越界而崩溃。条件中用的条件一直都是第一次查找获取的locationlenth

                //每次删完需重新定位子串的位置,保证信息同步。

                      substr = [str rangeOfString:@"png"];

                }

                NSLog(@"%@", str);

    //打印结果为: xxx.

     

  • 相关阅读:
    Linux_day01_primaryCommand
    Variational auto-encoder VS auto-encoder
    python yield generator 详解
    Paper Writing
    DTU_AI lecture 09
    DTU_AI lecture 08
    Attention mechanism
    Energy Journals
    TF + pytorch学习
    expRNN
  • 原文地址:https://www.cnblogs.com/JoelZeng/p/3454658.html
Copyright © 2011-2022 走看看