开发者

How to replace the Space with UnderScore( _ ) in the array in objective C

How to replace the Space with UnderSco开发者_Go百科re( _ ) in the array in objective C. The following is the code i am using to read the array data from the file,

NSString *g = [[NSString alloc]initWithCString:data];
    NSMutableString *tempGetAll = [[NSMutableString alloc]init];
    if(k>0){
        NSArray *lines = [g componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@""]];
        for (NSString* line in lines)
        {
          //[arrGetAll addObject: line];
          NSLog(@"%@",line) ;
          //NSLog(@"---------");

        }

    }
    k++;

The following is the output i am getting,

hi how r u 20.000

But i need the output in the following way,

hi_how_r_u:20.000

so how to replace the space with the Underscore.


There is a method stringByReplacingOccurrencesOfString:withString:

NSString* string1 = @"123 123 123";
NSString* string2 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSLog(@"%@", string2);

Result is

123_123_123


In order to create a string from an array by joining its elements you must use NSArray's:


- (NSString *)componentsJoinedByString:(NSString *)separator

In your case it is:

NSString *getAll = [lines componentsJoinedByString:@"_"];

Essentially "componentsSeparatedByCharactersInSet" splits a string to an array, "componentsJoinedByString" joins array components in one string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜