objective c - How can I replace certain words in a sentence with other words while maintaining the correct capitalization efficiently? -


as detailed in previous answer, https://stackoverflow.com/a/16458627/1633251, appears enumeratesubstringsinrange: faster separating string array guessed @ punctuation characters. however, don't understand how can efficiently maintain correct capitalization , punctuation (but ignoring punctuation within words i.e. apostrophes). note i'm new objective-c.

specifically, have string: @"my computer on fire! should do? need computer's files!" , want change every word longer 5 characters "boss" while preserving capitalization: @"my boss on boss! boss boss do? boss boss boss!"

here code want, updated handle numbers:

nsstring *original = @"my computer on fire @ 9:00 am! should do?"; nsstring *swapstring = @"boss";  nsmutablestring *modified = [nsmutablestring stringwithcapacity:[original length]]; __block nsuinteger lastcharoffset = 0;  [original enumeratesubstringsinrange:nsmakerange(0, [original length]) options:nsstringenumerationbywords // nsstringenumerationbycomposedcharactersequences // | nsstringenumerationsubstringnotrequired     usingblock:^(nsstring *substring, nsrange substringrange, nsrange enclosingrange, bool *stop)         {             //nslog(@"substring %@", substring);              nsstring *replacestring = substring;             if([substring length] > 2) {                 unichar origchar = [substring characteratindex:0];                 if(![[nscharacterset decimaldigitcharacterset] characterismember:origchar]) {                     replacestring = [[nscharacterset uppercaselettercharacterset] characterismember:origchar] ? [swapstring capitalizedstring] : swapstring;                 }             }             if(substringrange.location) {                 [modified appendstring:[original substringwithrange:nsmakerange(lastcharoffset, substringrange.location-lastcharoffset)]];             }             [modified appendstring:replacestring];             lastcharoffset = substringrange.location + substringrange.length;         } ];         // grab trailing punctuation         [modified appendstring:[original substringwithrange:nsmakerange(lastcharoffset, [original length] - lastcharoffset)]];     nslog(@"orig: %@", original);     nslog(@"modi: %@", modified); 

the output is:

orig: computer on fire @ 9:00 am! should do? modi: boss on boss @ 9:00 am! boss boss do? 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -