How to delete single characters in an UITextView - iphone

I have an UITextView which is for instance 380 characters in length:
NSLog(#"aTextView.text lenght %i", aTextView.text.length);
I now want to go through this text (backwards, char by char) and delete all characters which come before the last space (e.g. if the last words were "...this is an example", it want to reduce the string to "...this is an ":
for (int i = aTextView.text.length-1; i > 0; i--) {
NSString *checkedChar = [NSString stringWithFormat:#"%c", [aTextView.text characterAtIndex:i]];
NSLog(#"I currently check: %#", checkedChar);
if ([checkedChar isEqualToString:#" "]) {
// job done
i = 0; // this ends the loop
} else {
I need something like [aTextView.text removeCharacterAtIndex:i];
}
}
How do I achieve this? I couldn't find any methods in the docs and would be very grateful for suggestions.
EDIT:
NSString *myString = aTextView.text;
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch];
NSString *oldText = [myString subStringToIndex:range.location];
NSString *newText = [myString subStringFromIndex:range.location];
NSLog(#"++++ OLD TEXT ++++: %#", oldText);
NSLog(#"++++ NEW TEXT ++++: %#", newText);
aTextView.text = oldText;
This crashes my app... I am calling this from - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText
I get the error message: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString subStringToIndex:]: unrecognized selector sent to instance 0x4e33850'
And xCode gives me the warning the subStringToIndex may not respond...

You don't need a loop to do this - take a look at NSString' rangeOfString:options: and substringToIndex: methods. For example :
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch];
NSString *newString = [myString substringToIndex:range.location];
Hope that helps.
NB Don't forget to check that your string definitely contains a space ;)

This is very easy in iOS 5 or later:
// This is your delete button method.
-(IBAction)btnDelete:(id)sender
{
// txtView is UITextView
if([txtView.text length] > 0)
{
[txtView deleteBackward];
}
}

Related

Replacing instances of a character with two different characters in Objective-C

I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as "This is a message with $specially formatted$ content".
However, I need to change the '$' at the start of the special formatting with a '[' and the '$' at the end with ']'. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!
Is there a simple way to recognise a substring encapsulated by '$' and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple '$' substrings.
Thanks!
You can use regular expressions:
NSMutableString *str = [#"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#"[$1]"];
NSLog(#"%#", str);
// Output:
// Hello [World], foo [bar].
The pattern #"\\$([^$]*)\\$" searches for
$<zero_or_more_characters_which_are_not_a_dollarsign>$
and all occurrences are then replaced by [...]. The pattern contains so many backslashes because the $ must be escaped in the regular expression pattern.
There is also stringByReplacingMatchesInString if you want to create a new string instead of modifying the original string.
I think replaceOccurrencesOfString: won't work cause you have start$ and end$.
But if you seperate the Strings with [string componentsSeperatedByString:#"$"] you get an Array of substrings, so every second string is your "$specially formatted$"-string
This should work!
NSString *str = #"This is a message with $specially formatted$ content";
NSString *original = #"$";
NSString *replacement1 = #"[";
NSString *replacement2 = #"]";
BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
start = !start;
rOriginal = [str rangeOfString: original];
}
NSLog(#"%#", str);
Enjoy Programming!
// string = #"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:#"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
[out appendString:components[i]];
[out appendString: (i % 2) ? #"]" : #"[" ];
}
// out = #"This is a [special markup] sentence."
Try this one
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
if ([string characterAtIndex:i]=='$') {
if (open) {
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"["];
open=!open;
}
else{
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"]"];
open=!open;
}
}
}
NSLog(#"-->%#",string);
Output:
-->This is a message with [specially formatted] content. This is a message with [specially formatted] content

Add a character to a blank textfield

I'm new to xcode and am stuck on this one action.
I'm trying to add a "Negative" sign or "-" to a field when a button is clicked.
The following code works when someone enters a number into the field... it will add or remove a negative sign to it.
However, if the field is blank and you click on the button it throws an error.
Here's the code:
- (IBAction)fPosNeg:(id)sender {
NSMutableString *str = [userFahrenheit.text mutableCopy];
char iChar = [str characterAtIndex:0];
if (iChar == '-') {
userFahrenheit.text = [userFahrenheit.text substringFromIndex:1];
} else if (iChar != '-') {
[str insertString:#"-" atIndex:0];
userFahrenheit.text = str;
} else {
userFahrenheit.text = [NSString stringWithFormat:#"-"];
}
}
Here's the error:
Terminating app due to uncaught exception 'NSRangeException', reason:
'-[__NSCFString characterAtIndex:]: Range or index out of bounds'
You need to put a check before calling this -> [str characterAtIndex:0];
check will be
if(![str isEqualToString:#""]) // so that if string is blank, you cant access its character at index 0
NSMutableString *str = [NSMutableString stringWithString:#"-Test"];
char test = [str characterAtIndex:0];
NSMutableString *strFinal;
if (test == '-') {
strFinal = [NSMutableString stringWithString:[str substringFromIndex:1]];
}
else if (test != '-') {
[str insertString:#"-" atIndex:0];
strFinal=str;
}
else {
strFinal=[NSString stringWithFormat:#"-"];
}
NSLog(#"%#",strFinal);
You can also use this.
I think it's solve your problem.

Objective-c Substring Range Exception

I am creating an imap client. I want to parse body and header of incoming data but it crashes. I couldn't understand why it crashes and gives substring out of range error. How can I fix it?
I only want to check if the incoming string contains "FETCH" so I parse data, since string comes like
* FETCH or * 1 FETCH I thought checking isEqualToString range of (4,6) would be enough but that didn't work.
- (NSString*) readLine
{
NSMutableData* data = [[NSMutableData alloc] init];
unsigned char c;
for (;;) {
recv(socket_, &c, sizeof(c), 0);
if (c == '\n') {
NSString* s = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSString *str = [s substringWithRange:NSMakeRange(4, 6)];
if( [str isEqualToString:#"FETCH "]){
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:#"}" intoString:nil];
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"}" intoString:nil];
if([scanner scanUpToString:#"*" intoString:&substring]) {
// If the space immediately followed the }, this will be skipped
[substrings addObject:substring];
}
[scanner scanUpToString:#"}" intoString:nil]; // Scan all characters before next }
}
NSString *email;
[emailList addObject:#"Select an Email"];
for(int i=0; i<substrings.count;i++){
email = [substrings objectAtIndex:i];
[emailList addObject:email]; // add emails in emailList
}
[substrings release];
}
if (nil != s) {
NSLog(#"%#",s);
}
[data release];
return [s autorelease];
}
else {
[data appendBytes: &c length: 1];
}
}
return nil;
}
output is:
* 1 FETCH (BODY[HEADER.FIELDS (FROM SUBJECT DATE)] {149}
2011-11-07 23:32:24.363 SwitchDeneme[327:bc03] Date: Mon, 07 Nov 2011 17:00:25 -0500 (EST)
2011-11-07 23:32:24.364 SwitchDeneme[327:bc03] From: "AOLWelcomeInfo" <AOLWelcomeInfo#message.aol.com>
2011-11-07 23:32:24.365 SwitchDeneme[327:bc03] Subject: Welcome to Your New Email Account!
2011-11-07 23:32:24.367 SwitchDeneme[327:bc03] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds'
terminate called throwing an exceptionsharedlibrary apply-load-rules all
The problem is that your string is likely shorter than 7 characters, meaning it does not have an index of 6.
Try something more like this:
NSRange range = [someString rangeOfString:#"FETCH "];
if( range.location != NSNotFound ) {
//found it... so now do you processing...
}
You allocate and initialize an NSData object, then use that empty data object to initialize a string, so that string is empty.

How to detect UISearchBar is containing blank spaces only

How to detect if UISearchBar contains only blank spaces not any other character or string and replace it with #""?
You can trim the string with a character set containing whitespace using the NSString stringByTrimmingCharactersInSet message (using the whitespaceCharacterSet):
NSString * searchString = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (![searchString length])
// return ... search bar was just whitespace
You can check as
[yourSearchBar.text isEqualToString:#""]
Hope it helps.
if([searchBar.text isEqualToString:#""] && [searchBar.text length] ==0){
// Blank Space in searchbar
else{
// Do Search
}
Use isEqualToString method of NSString
Use stringByTrimmingCharactersInSet to trim the character from NSString.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Use as below.
NSString* myString = mySearchBar.text
myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Here's how you detect and replace it: (assuming the UISearchField is called searchBar)
NSString*replacement;
if ([searchBar.text isEqualToString:#" "])
{
replacement = [NSString stringByReplacingOccurancesOfString:#" " withString:#""];
}
searchBar.text = replacement;
Have a look in the Apple Documentation for NSString for more.
Edit:
If you have more than once space, do this:
NSString *s = [someString stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [someString length])
];
searchBar.text = s;
This worked for me: if you are using #"" or length already to control say a button then this version really does detect the whitespace, if a space has been entered...
if([activeField.text isEqualToString:#" "] && [activeField.text length] ==1){
// Blank Space in searchbar
{
// an alert example
}

How to count '\n' in an UITextView

I got a headache trying to count returns (\n) in my UITextView. As you'll soon realise, I'm a bloody beginner and here is my theory of what I've come up with, but there are many gaps...
- (IBAction)countReturns:(id)sender {
int returns;
while ((textView = getchar()) != endOfString [if there is such a thing?])
{
if (textView = getchar()) == '\n') {
returns++;
}
}
NSString *newText = [[NSString alloc] initWithFormat:#"Number of returns: %d", returns];
numberReturns.text = newText;
[newText release];
}
I checked other questions on here, but people are usually (in my eyes) lost in some details which I don't understand. Any help would be very much appreciated! Thanks for your patience.
You can simply
UITextView *theview; //remove this line, and change future theview to your veiw
NSString *thestring; //for storing a string from your view
int returnint = 0;
thestring = [NSString stringWithFormat:#"%#",[theview text]];
for (int temp = 0; temp < [thestring length]; temp++){ //run through the string
if ([thestring characterAtIndex: temp] == '\n')
returnint++;
}
NSArray *newlines = [textView.text componentsSeparatedByString:#"\n"];
int returns = ([newlines count]-1)
Should work. Keep in mind this isn't such a great idea if you have a gia-normous string, but it's quick, dirty and easy to implement.
there are a lot of ways to do that. Here is one:
NSString *str = #"FooBar\n\nBaz...\n\nABC\n";
NSString *tmpStr = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSInteger count = [str length] - [tmpStr length];
NSLog(#"Count: %d", count);