B. Money
B. Money

Reputation: 931

Why is Xcode adding whitespace to end of String?

I'm a noob to iphone development and I am having a very weird issue with xcode. For some reason, it is randomly adding trailing whitespace to the end of my strings. My initial string value is parsed from an xml and then from there I attempt grab the last section of the string. This is proving to be difficult because of this random whitespace. Any help is greatly appreciated.

MY CODE

//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.

Upvotes: 1

Views: 766

Answers (3)

nsgulliver
nsgulliver

Reputation: 12671

You could try to remove the newline also from the string. Your string contains not only white spaces but also new-line.

NSString *trimmmedContent = [contents stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Upvotes: 3

Hot Licks
Hot Licks

Reputation: 47729

Note that you probably don't have <title>March 15 2013 Metals Commentary: Thomas Vitiello</title>. More likely you have:

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

Unless you use an option to prevent it, the XML parser will generally include the whitespace between tags, so you get that trailing newline.

Upvotes: 2

Caleb
Caleb

Reputation: 125007

You're using whiteSpaceCharacterSet, which is described like this:

Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

But from your own question, it appears that there's a newline in your string. Notice how the length appears on a different line from the string, even though there's no newline in your format string. A newline isn't one of the characters that you're trimming. To solve the problem, use whitespaceAndNewlineCharacterSet instead.

Upvotes: 1

Related Questions