1

我是 iphone 开发的菜鸟,我对 xcode 有一个非常奇怪的问题。出于某种原因,它会在我的字符串末尾随机添加尾随空格。我的初始字符串值是从 xml 解析的,然后我尝试从那里获取字符串的最后一部分。由于这个随机的空白,这被证明是困难的。任何帮助是极大的赞赏。

我的代码

//initial String 
<title>March 15 2013 Metals Commentary: Thomas Vitiello</title>

//Parsing
NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSLog(@"myname: %@ %i", name, name.length);

//Log at this point
myname: March 15 PM Metals Commentary: Thomas Vitiello
         59

//Attempt at Removing Whitespace
NSArray *lastName=[name componentsSeparatedByString:@" "];
name = [[lastName objectAtIndex:6]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"myname: %@ %i", name, name.length);

//Log at this point
myname: Vitiello
9 //<--Should be 8, not 9.  This annoying whitespace is also particularly long, taking more than 1 character space, despite obviously being 1 character long.
4

3 回答 3

3

您也可以尝试从字符串中删除换行符。您的字符串不仅包含空格,还包含换行符。

NSString *trimmmedContent = [contents stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
于 2013-03-17T18:20:14.703 回答
2

请注意,您可能没有<title>March 15 2013 Metals Commentary: Thomas Vitiello</title>. 您更有可能:

<title>March 15 2013 Metals Commentary: Thomas Vitiello
</title>

除非您使用选项来阻止它,否则 XML 解析器通常会在标签之间包含空格,因此您会得到尾随的换行符。

于 2013-03-17T18:22:06.930 回答
1

您正在使用whiteSpaceCharacterSet,其描述如下:

返回仅包含行内空白字符空格 (U+0020) 和制表符 (U+0009) 的字符集。

但是从您自己的问题来看,您的字符串中似乎有一个换行符。请注意长度如何出现在与字符串不同的行上,即使您的格式字符串中没有换行符。换行符不是您要修剪的字符之一。要解决问题,请whitespaceAndNewlineCharacterSet改用。

于 2013-03-17T18:21:38.427 回答