1

I'm loading a UTF-8 encoded text file into an array. At several places in the text file there are blank lines, with no spaces.

In this conditional:

tempstring = [array objectAtIndex:index];
if( [tempstring isEqualToString:@""] == NO ) {
    // do something
}

The result is always NO. I NSLog the strings, but I don't see any character in the console on the blank lines. The NSLog also shows the blank lines having the length of 1.

How can I correct this conditional to work?

TigerCoding
  • 8,710
  • 10
  • 47
  • 72

3 Answers3

3

Try removing the whitespace from the NSString from the NSArray before comparing it. See here: Collapse sequences of white space into a single character and trim string

Community
  • 1
  • 1
edc1591
  • 10,146
  • 6
  • 40
  • 63
  • Perfect: tempstring= [tempstring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; – TigerCoding Apr 08 '11 at 12:26
0

Blank lines are usually not completely blank - they still have a newline at the end, even when they have nothing else. Try this:

tempstring = [array objectAtIndex:index];
if( [tempstring isEqualToString:@"\n"] == NO ) {
    // do something
}
Sherm Pendley
  • 13,556
  • 3
  • 45
  • 57
  • If that fails, but stripping whitespace works, that means you don't have blank lines - you have lines with one or more whitespace characters in them. – Sherm Pendley Apr 08 '11 at 12:30
  • strange, whitespace doesn't show in the text file in xcode. :| But what you say makes sense. Could it be added when it's loaded into the array? array = [self loadTextFileNamed:filename]; – TigerCoding Apr 08 '11 at 12:41
  • 1
    must be newline char, not whitespace – TigerCoding Apr 08 '11 at 12:44
  • I don't know what -loadTextFileNamed: is doing - you wrote it, not me. :-) If it's using `-componentsSeparatedByString:@"\n"` to split the string into lines, then a DOS text file with \r\n line endings could confuse it, and leave the \r at the end of each line. If that's the case, and handling such files is a requirement, you should split with `-componentsSeparatedByCharacterSet:[NSCharacterSet newlineCharacterSet]` instead. IMHO, it's better to solve problems at their source, than to work around them elsewhere. – Sherm Pendley Apr 08 '11 at 13:00
  • Blah, typo. Make that: `-componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]`. – Sherm Pendley Apr 08 '11 at 13:06
-1

tempstring = [array objectAtIndex:index];

if( [tempstring isEqualToString:@""] == FALSE && tempstring != nil ) {

// do something

}

Chetan Bhalara
  • 10,326
  • 6
  • 32
  • 51