separate words with line breaks (\n) into separate words

Discussion in 'iOS Programming' started by stoopkitty, Feb 11, 2011.

  1. stoopkitty macrumors member

    Joined:
    Jan 26, 2010
    #1
    I am trying to write code that while looping through an array of strings, checks to see if each string has line breaks and if it does, it removes the line breaks and puts the separate words back into the array. (see below for example)

    {@"The", @"quick" @"brown\n\nfox", @"jumps"} --> {@"The", @"quick" @"brown", @"fox", @"jumps"}

    basically, i am looping through a NSMutableArray (words) and getting each word. the only problem is, the text is from a UITextView so there could be line breaks in the string (which is fine, they should be able to enter line breaks). anyway, words is an array containing each word in the string separated by spaces, but the problem is some of the "words" in the array contain "\n", usually in the middle of the string. to fix this, i decided to make a "subWords" array containing all of the words in the current string from objectAtIndex of words separated by "\n". It would then replace the word in the words array which it just got the separated parts of, with the word at index=0 of subArray, and then if subArray has anymore values, it would add those into the words array after the ones it just added. (sorry if that was a little confusing, if you didnt understand it at all tell me and i can try to clarify). I did this, and I thought i did it pretty well, but

    I am getting an error at the line where it is marked. The error is NSInvalidArgumentException, which the documentation says this method throws if its "withObject" paramater is nil. however, i have debugged this, and subWordsAtZero, the string I am passing in for its "withObject" paramater is always equal to a word, just because of logic and because i have checked it in the debugger. am i missing something? thanks!!

    Code:
    //inside for loop (int c, c=0, c++), words contained in mutablearray "words", "subwords" defined previously as mutablearray, but no value set yet
    subWords = [NSArray arrayWithArray:[[words objectAtIndex:c] componentsSeparatedByString:@"\n"]];
    subWordsAtZero = [subWords objectAtIndex:0];
    if ([subWords count] > 1) {
    	[words replaceObjectAtIndex:c withObject:subWordsAtZero]; //ERROR IS HERE
    	for (int d = 1; d < [subWords count]; d++){
    		if (![[subWords objectAtIndex:d] isEqualToString:@""]) {
    				[words insertObject:[subWords objectAtIndex:d] atIndex:c+d];
    		}
    	}
    }
     
  2. stoopkitty thread starter macrumors member

    Joined:
    Jan 26, 2010
    #2
    Nevermind, I figured it out. The code above is valid, I didnt initialize my "words" array properly (i defined it as an NSMutableArray, but then said [NSArray alloc], which confused it)

    Thanks everyone!
     

Share This Page