gpt4 book ai didi

ios - 用换行符替换多个空格,但保留单个空格

转载 作者:行者123 更新时间:2023-11-28 22:15:55 25 4
gpt4 key购买 nike

我正在尝试操作一个 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

Here's a bit of logic I have been working on. I'm not sure if it's correct.

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

最佳答案

您可以使用 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);

关于ios - 用换行符替换多个空格,但保留单个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21694404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com