IOS: stringByReplacingOccurrencesOfString don't work - ios

filepath:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/photo2.jpg
photonumber:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/2
index = 2;
NSString *nextSequentialFile =
[filePath stringByReplacingOccurrencesOfString:photoNumber
withString:[NSString stringWithFormat:#"%d", index+1]
options:NSBackwardsSearch
range:NSMakeRange(0, filePath.length)];
the result is ever
nextsequenzial:/var/mobile/Applications/BA7AE6F8-C7EA-4601-A5F4-30E3C57FE948/Documents/photo2.jpg
why?
it must be /photo3.jpg

filepath doesn't contain photonumber, so there's nothing to replace. Note that photonumber ends with /Documents/2 while filepath contains /Documents/photo2.jpg.
photonumber needs to be changed to end in /Documents/photo2 and the replacement string needs to be changed to [NSString stringWithFormat:#"/photo%d", index+1].

Related

iOS get substring from a string?

I'v a string like - NSString * str = #"a. System discharges to the ground or to surface waters\n\nb. System causes sewage backup in structure\n\nc. “Black Soil” above system or drain field\n\n\nd. Ponding or puddles around tank, distribution boxes, or drain field" and want some specific substring from str for e.g. b. System causes sewage backup in structure
i have tried
NSRange r1 = [str rangeOfString:#"b. "];
NSString* substr = [str substringFromIndex:r1.location];
NSString* s1 = [substr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
but i got whole string starting from b. System....
What i'm doing wrong?
Try something like:
NSRange r1 = [str rangeOfString:#"b. "];
NSString *substr = [str substringFromIndex:r1.location];
NSRange r2 = [substr rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
NSString *s1 = [substr substringToIndex:r2.location];
You have your starting point right but you also need to make it right at the end point. This code might help you. Though this mayn't be the exact thing that you might be looking for, it will surely help you in getting the desired result.
NSString *badStr = [NSString stringWithUTF8String:[response bytes]];
NSString *goodStr = [badStr substringFromIndex:76];
NSString *finalStr = [goodStr substringToIndex:[goodStr length]-9];
Basically, this code removes the unwanted characters from the beginning as well as from the ending of the string.
Hope this helps.

iOS: changing NSString value

Will this bit of code produce any memory leaks? Is it the correct way to change NSString values?
NSString * enemiesAndElementsTextureFileName = #"bla bla";
enemiesAndElementsTextureFileName = #"bl";
That way of doing it won't cause any memory leaks and it is indeed correct. In this case you wouldn't need an NSMutableString because you aren't altering the string literal itself, you are simply replacing the string value with a new one (replacing #"bla bla" with #"bl").
In this case, however, your string will now be 'bl', so you can delete that first line value and just have NSString * enemiesAndElementsTextureFileName = #"bl";
Yes NSString allocated once. This is one of the way
Yes, use NSMutableString with the following method as your needs:
// Allocate
NSMutableString *str = [[NSMutableString alloc] initWithCapacity:10];
// set string content
[str setString:#"1234"];
// Append
[str appendString:#"567"];
// Concat
[str appendFormat:#"age is %i and height is %.2f", 27, 1.55f];
// Replace
NSRange range = [str rangeOfString:#"height"];//查找字符串height的位置
[str replaceCharactersInRange:range withString:#"no"];
// Insert
[str insertString:#"abc" atIndex:2];
// Delete
range = [str rangeOfString:#"age"];
[str deleteCharactersInRange:range];
NSLog(#"%#", str);

iOS finding string within a string

Hello everyone I am trying find a string inside a string
lets say I have a string:
word1/word2/word3
I want to find the word from the end of the string to the last "/"
so what I will get from that string is:
Word3
How do I do that?
Thanks!
You are looking for the componentsSeparatedByString: method
NSString *originalString = #"word1/word2/word3";
NSArray *separatedArray = [originalString componentsSeparatedByString:#"/"];
NSString *lastObject = [separatedArray lastObject]; //word3
once check this one By using this one you'l get last pathcomponent values,
NSString* theFileName = #"how /are / you ";
NSString *str1=[theFileName lastPathComponent];
NSLog(#"%#",str1);
By using lastPathComponent you'l get the last path component directly no need to take array for separate the string.
you must use NSScanner class to split substring.
check this.
Objective C: How to extract part of a String (e.g. start with '#')
NSString *string = #"word1/word2/word3"
NSArray *arr = [string componentsSeperatedByString:#"/"];
NSSting *str = [arr lastObject];
You can find it also with this way:
NSMutableString *string=[NSMutableString stringWithString:#"word1/word2/word3"];
NSRange range=[string rangeOfString:#"/" options:NSBackwardsSearch];
NSString *subString=[string substringFromIndex:range.location+1];
NSRegularExpression or NSString rangeOfString:options:range:locale: (with options to search backwards).
The answer really depends on exactly what the input string will contain (how consistent it is).

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

if statement with empty UILabel

I have a UILabel that is loaded form a text file. Sometimes the text file has something in it and sometimes it is empty. So sometimes the UILabel is blank and sometimes it has text in it.
I want to write an if statement that says if the UILabel is blank do one thing else if it has text in it do another thing.
I have tried
if (self.label.text = NULL)
and
if (self.label.text = #"")
but it isn't working correctly.
With the if (self.label.text = #""), I get the if statement to happen but the else statement doesn't work.
Here is my code
NSString *stuff3 = #"/Stuff";
NSString *titleName = [familyDictionary objectForKey:#"identity"];
NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
NSString *stuffPath3 = [documentsDirectory3 stringByAppendingPathComponent:stuff3];
NSString *fullPath3 = [stuffPath3 stringByAppendingPathComponent:titleName];
self.title = [NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"full path 3 >>>%#",fullPath3);
NSString *stuff4 = #"/Stuff/Objects";
NSString *textName3 = [familyDictionary objectForKey:#"identity"];
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *stuffPath = [documentsDirectory2 stringByAppendingPathComponent:stuff4];
NSString *fullPath2 = [stuffPath stringByAppendingPathComponent:textName3];
self.wordlabel.text = [NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL];
//Now load the image at fullPath and install it into our image view's image property.
NSLog(#"full path 3 >>>%#",fullPath2);
if(self.wordlabel.text = #"")
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
else
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
You're doing it wrong, wrong.
Wrong 1: = is the assignment operator, == is the equality operator. You're using the assignment operator inside an if statement, you should at least be getting a compiler warning about that.
Wrong 2: Even if you had that bit right, it's the wrong way to compare strings. Use isEqualToString: or check length as in the other answers.
Wrong 3: The logic should probably be based on the strings before you assign them to the label, not by reading back what is in the label. It's a cleaner MVC implementation.
What you are doing is comparing pointers, which doesn't work with strings. Use this
if ([self.wordlabel.text isEqualToString:#"thestring"])
you should ideally use:
if ([self.label.text length] > 0)
When you say self.label.text = #"" you are changing your label's text. = is the assignment operator. == is the comparison operator.
However, to compare strings, you must use the comparison method [self.label.text isEqualToString:#""], otherwise you are just comparing pointers.

Resources