简体   繁体   English

在NSString中的句号或问号前修剪空格

[英]Trim spaces before full stop or question mark in an NSString

If I have a string like "How are you doing ?" 如果我输入"How are you doing ?"最近"How are you doing ?"类的字符串 or "I am fine ." "I am fine ."

how can I get - 我怎样才能得到 -

"How are you doing?" or "I am fine." "I am fine."

I want to remove whitespace between the last word and "?" 我想删除最后一个单词和“?”之间的空格。 or "." 要么 ”。”

You could use stringByReplacingOccurrencesOfString . 您可以使用stringByReplacingOccurrencesOfString And with the use of the NSRegularExpressionSearch option, you could handle all of the different permutations in a single statement: 通过使用NSRegularExpressionSearch选项,您可以在一个语句中处理所有不同的排列:

NSString *result = [string stringByReplacingOccurrencesOfString:@"\\s+([.?])"
                                                     withString:@"$1"
                                                        options:NSRegularExpressionSearch
                                                          range:NSMakeRange(0, [string length])];

Regular expressions can be cryptic (see NSRegularExpression documentation for more information), but this says "find any strings that consists of one or more whitespace characters (space, tab, newline, etc.) followed by a full stop (period) or question mark and replace with just the full stop or question mark you found." 正则表达式可以是含糊的 (有关更多信息,请参见NSRegularExpression文档 ),但这表示“查找由一个或多个空格字符(空格,制表符,换行符等),后跟句号(句点)或问号组成的任何字符串。并以您发现的句号或问号代替。” You can refine that as needed, but hopefully this illustrates the concept. 您可以根据需要进行优化,但是希望可以说明这一概念。

I don't see an immediate way to do that. 我看不到立即执行此操作的方法。 I would just search the range of any character that you want - like in your case question marks and dots - and check if there's a space before it, and in case remove the space. 我只是搜索您想要的任何字符的范围(例如在您的情况下问号和点),并检查其前面是否有空格,以防删除空格。 This is an example: 这是一个例子:

NSString* str= @"How are you doing ?";
NSRange range= [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @".?"]];
if(range.location!= NSNotFound)
{
    if(range.location>0 && [str characterAtIndex: range.location-1]==' ')
    {
        str= [str stringByReplacingCharactersInRange: NSMakeRange(range.location-1, 1) withString: @""];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM