NSString Problem - iphone

NSRange rangetxt={0,(index-1)};
NSString *tempStr= textBox.text;
NSString *tempTextBox=[tempStr substringWithRange:rangetxt];
Hi Everyone,
I want to know why my pasted code isn't working properly, when the compiler passes substringWithRange It hung up and do not assign any value to tempTextBox, Secondly I've tried the NSString function substringToIndex as well yet its not working too, My objective is to skip the last character while copying tempStr to tempTextBox.
Regards
MGD

I had test this code and it works:
NSString *strTest = #"Word";
NSRange range = {0, 3};
NSString *strTemp = [strTest substringWithRange: range];
The result: strTemp = "Wor"
So the problem is something else: index is not proper or textBox.text is maybe empty.
Put the breakpoint on your substringWithRange: line and look at the values of index and tempStr before problem appears.

You should use NSMakeRange(loc, len) to create a NSRange object instead of using {}.

You don't show the code that's initialising index. My guess is it's out of range. Note that substringWithRange raises an NSRangeException if any part of the range lies beyond the end of the receiver.
Try this:
NSString *tempStr = textBox.text;
NSRange rangetxt;
if ([tempStr length] > 0)
rangetxt = NSMakeRange(0, [tempStr length] - 1);
else
rangetxt = NSMakeRange(0, 0);
NSString *tempTextBox = [tempStr substringWithRange:rangetxt];

I think i got my problem solved, During the debug when i pass through these line my gdb says "Timed out fetching data. Variable display may be inaccurate" so i found the solution just placed my break point after the initialization of the NSString objects
Thanks for Help Everyone
MGD

Related

Get first sentence of textview

I am trying to get the first sentence of a text view. I have the following code but am getting an out of bounds error. Thank You. Or are there any ways that aren't really complex.
-(IBAction)next:(id)sender
{
NSRange ran = [[tv.text substringFromIndex:lastLocation] rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * getRidOfFirstHalfString = [[tv.text substringFromIndex:lastLocation] substringToIndex:ran.location];
NSLog(#"%#",getRidOfFirstHalfString);
lastLocation+=getRidOfFirstHalfString.length;
}
How about:
NSString *finalString = [[tv.text componentsSeparatedByString:#"."] objectAtIndex:0] // Get the 1st part (left part) of the separated string
Go through the textview's text and divide the text into separate components where you find a period by calling componentsSeperatedByString on tv.text. You want the first sentence, which would be the 0th object in the array.
I know you've already accepted an answer to this question, but you might want to consider using the text view's tokenizer instead of just searching for the string ". " The tokenizer will automatically handle punctuation like !, ?, and closing quotes. You can use it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextRange *range = [tokenizer rangeEnclosingPosition:textView.beginningOfDocument
withGranularity:UITextGranularitySentence
inDirection:UITextStorageDirectionForward];
NSString *firstSentence = [textView textInRange:range];
If you want to enumerate all of the sentences, you can do it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *start = textView.beginningOfDocument;
while (![start isEqual:textView.endOfDocument]) {
UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularitySentence inDirection:UITextStorageDirectionForward];
NSString *sentence = [textView textInRange:[textView textRangeFromPosition:start toPosition:end]];
NSLog(#"sentence=%#", sentence);
start = end;
}
Try checking that the substring was actually found.
NSRange ran = [tv.text rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * selectedString = [tv.text substringToIndex:ran.location];
NSLog(#"%#",selectedString);
}
You could alternatively try using NSScanner like this:
NSString *firstSentence = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:tv.text];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"."];
[scanner scanUpToCharactersFromSet:set intoString:&firstSentence];
I'm not sure if you want this, but since you want the first sentence, you could append a period (you probably know how to do this, but it doesn't hurt to show it anyway):
firstSentence = [firstSentence stringByAppendingFormat:#"."];
Hope this helps!
PS: If it didn't work for you, maybe the text view doesn't actually contain any text.

cut nsstring after a special character in iphone

I'm new in iPhone, I want to cut a string after a special character, lets take this example
"works.php" , I want to remove ".php" from this string meaning that I want to remove what's after "."
what is the code to do that ??
thanks in Advance.
It seems you want to use -stringByDeletingPathExtension.
[#"works.php" stringByDeletingPathExtension] // becomes #"works".
Note that this method deletes path extensions, which is not exactly the same as "remove what's after a dot". Please read the reference I've linked above for detail.
If you really just need to remove the string after the last dot, just use the conventional algorithm of (1) find the last dot (2) get a substring until the last dot:
NSString* input = #"works.php";
NSRange lastDotRange = [input rangeOfString:#"." options:NSBackwardsSearch];
if (lastDotRange.location != NSNotFound) {
return [input substringToIndex:lastDotRange.location];
} else {
return input;
}
For the specific example you can use:
- (NSString *)stringByDeletingPathExtension
The more general way to do what you want is:
NSString *originalString = #"works.php";
NSString *finalString =
[[originalString componentsSeparatedByString:#"."] objectAtIndex: 0];
You can replace the dot character with any character you want.
You can use:
myString = #"anything.php";
myString = [myString stringByReplacingOccurrencesOfString:#".php" withString:#""];
The advantage of this is that you can put anything to remove, not only a path. For example:
myString = #"anything-123";
myString = [myString stringByReplacingOccurrencesOfString:#"-123" withString:#""];
Another approach is NSRange and substringWithRange if you want other removing options..

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

Check NSMakeRange is Able to take range or Not

I am currently using the below code to take the substring
NSString *s1 = [stringName substringWithRange: NSMakeRange(0, 2)];
NSString *s2 = [stringName substringWithRange: NSMakeRange(2, 4)];
NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length])];
Here, how to check the range is valid or not because i am not able to length of string to validate because it may differ on time. Please help me in this issue..
For s3, you're starting at position and ask for exactly as many characters as there are in the string. But since you're starting at position 6, you're asking for 6 characters too many. You need to do:
NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length] - 6)];
As the apple documentation says ..
substringWithRange:
Returns a string object containing the characters of the receiver that lie within a given range.
- (NSString *)substringWithRange:(NSRange)aRange
aRange
A range. The range must not exceed the bounds of the receiver.
You need to check every time when you construct an NSMakeRange(), whether the Range you specified within the length of your String OR not ... by Using some if and else condition

How to do a backwards search to find the 2nd space/blank and replace it with another string?

it's me again. I've asked a question similar to this just awhile ago but this question is a bit more complex. I was planning on using RegexKitLite to do what I needed to do but I believe this can be done with out it. I have a NSString that has some words with spaces/blanks in it and I'm wanting to get the very last space in the string that is to the left of the last word. Example String below:
NSString *string = #"Here is an example string HELLO ";
As you can see in the string above there is a space/blank at the very end of the string. I'm wanting to be able to get the space/blank to the left of HELLO and replace it with my own text/string. I'm working on using the NSString's NSBackwardsSearch but it's not working.
NSString *spaceReplacement = #"text that i want";
NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:#" " withString:spaceReplacement];
NSLog(#"%#", replaced);
Any help would help, I'm just tired of trying to fix this thing, it's driving me bonkers. I thought I could do this with RegexKitLite but the learning curve for that is too steep for me considering my timeframe I'm working with. I'm glad Jacob R. referred me to use NSString's methods :-)
This solution assumes you always have a space at the end of your string... it should convert
Here is an example string HELLO
... to:
Here is an example stringtext that i wantHELLO
... since that's what I understood you wanted to do.
Here's the code:
NSString *string = #"Here is an example string HELLO ";
NSRange rangeToSearch = NSMakeRange(0, [string length] - 1); // get a range without the space character
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" " options:NSBackwardsSearch range:rangeToSearch];
NSString *spaceReplacement = #"text that i want";
NSString *result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace withString:spaceReplacement];
The trick is to use the [NSString rangeOfString:options:range:] method.
Note: If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
Disclaimer: I haven't tested the code, but it should compile and work just fine.
Something like this should work:
NSString *string = #"Here is an example string HELLO ";
if ([string hasSuffix:#" "]) {
NSString *spaceReplacement = #"text that i want";
NSString *replacedString = [[string substringToIndex:
[string length]] stringByAppendingString:spaceReplacement];
NSLog(#"replacedString == %#", replacedString);
}
To solve #Senseful note
If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
I had added one line into code that helps in such situations and make code more universal:
// Some income sting
NSString * string = #"Here is an example string HELLO ";
// clear string from whitespace in end on string
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange rangeToSearch = NSMakeRange(0, [string length]);
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" "
options:NSBackwardsSearch
range:rangeToSearch];
// Replaed with String
NSString * spaceReplacement = #"text that i want";
NSString * result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace
withString:spaceReplacement];