用换行符替换多个空格但留下单个空格

时间:2014-02-11 06:09:16

标签: ios objective-c string cocoa nsstring

我正试图操纵NSString。我想结束输出。如果一行中有多个空格,则应使用换行符替换它们。

NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

NSLog()的所需输出:

Name: Tom Smith                  
Old address     
street name : 31 Fox Road                  
Dixton         
0000

这是我一直在努力的一些逻辑。我不确定它是否正确。

    if (word_spacing > 1)
        insert word in new line "\n"
    else
        carry on from the same line

5 个答案:

答案 0 :(得分:2)

您可以使用NSCharacterSetcomponentsSeparatedByString

来完成此操作

解决方案:

// Your string
NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

// Seperating words which have more than 1 space with another word
NSArray *components    = [myString componentsSeparatedByString:@"  "];
NSString *newString    = @"";
NSString *oldString    = @"";
for (NSString *tempString in components)
{
    // Creating new string
    newString = [oldString stringByAppendingString:[tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

    // Avoiding new line characters or extra spaces contained in the array
    if (![oldString isEqualToString:newString])
    {
        newString = [newString stringByAppendingString:@"\n"];
        oldString = newString;
    }
}
NSLog(@"%@",newString);

您可以使用NSRegularExpression

NSString *pattern = [NSString stringWithFormat:@"  {2,%d}",[myString length]];

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

NSString *output = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:@"\n"];
NSLog(@"%@", output);

答案 1 :(得分:0)

您可以尝试使用:

NSArray *results = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]]

返回一个数组,其中包含接收器中的子串,这些子串已被给定集合中的字符分割。

一旦你有了循环结果递增2,你就会得到键值对。然后,您可以使用以下方法对每个键值对的值进行某种修剪:

NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceCharacterSet]]; 

答案 2 :(得分:0)

你可以按照你想要的字符(在你的情况下有多个空格)分割字符串,如下所示:

NSArray * components = [myString componentsSeparatedByString: @"  "];

然后你可以打印出每个组件,然后打印换行符:

for (NSString * component in components) {
    NSLog(@"%@\n",component);
}

答案 3 :(得分:0)

如果您在字符串之间有不可预测性并且想要用new line替换多个空格,那么您应该使用正则表达式。您正在使用的正则表达式将无效,因为它选择空格one or more time但实际上您想要选择two or more times

我知道这个帖子已经解决但是看看这个例子:

NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}" options:NSRegularExpressionCaseInsensitive error:&error];

NSArray *arr = [regex matchesInString:myString options:NSMatchingReportCompletion range:NSMakeRange(0, [myString length])];

arr = [[arr reverseObjectEnumerator] allObjects];

for (NSTextCheckingResult *str in arr) {
    myString = [myString stringByReplacingCharactersInRange:[str range] withString:@"\n"]; }

NSLog(@"%@", myString);

输出日志:

Name: Tom Smith
Old address
street name : 31 Fox Road
Dixton
0000

Live Demo

答案 4 :(得分:0)

//调用如下方法:

    NSString *descriptionStr = [self stringByRemovingBlankLines:string];;

//方法

- (NSString *)stringByRemovingBlankLines : (NSString *)stringValue
{
NSScanner *scan = [NSScanner scannerWithString:stringValue];
NSMutableString *string = NSMutableString.new;
while (!scan.isAtEnd) {
    [scan scanCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:NULL];
    NSString *line = nil;
    [scan scanUpToCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:&line];
    if (line) [string appendFormat:@"%@\n",line];
}
if (string.length) [string deleteCharactersInRange:(NSRange){string.length-1,1}]; // drop last '\n'
return string;
}