How to selectively trim an NSMutableString?

可紊 提交于 2019-12-12 02:24:24

问题


I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?

Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".

Any help is very much appreciated!


回答1:


TESTED CODE: 100% WORKS

NSString *inputString=@"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";

NSArray *array= [inputString componentsSeparatedByString:@"_"];

if ([array count]>0) {

    NSString *resultedString=[array objectAtIndex:0];


    NSLog(@" resultedString IS - %@",resultedString);



}

OUTPUT:

resultedString IS - MobileSafari



回答2:


Given that you always need to extract the character upto the first underscore; use the following method;

NSArray *stringParts = [yourString componentsSeparatedByString:@"_"];

The first object in the array would be the extracted part you need I would think.




回答3:


If you know the format of the string is always like that, it can be easy.

Just use NSString's componentsSeparatedByString: documented here.

In your case you could do this:

NSString *source = @"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";

NSArray *seperatedSubStrings = [source componentsSeparatedByString:@"_"];

NSString *result = [seperatedSubStrings objectAtIndex:0];

@"MobileSafari" would be at index 0, @"2011-09-10-155814" at index 1, and @"Jareds-iPhone.plist" and at index 2.




回答4:


Try this :

NSString *strComplete = @"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";  
NSArray *arr = [strComplete componentsSeparatedByString:@"_"];  
NSString *str1 = [arr objectAtIndex:0];  
NSString *str2 = [arr objectAtIndex:1];  
NSString *str3 = [arr objectAtIndex:2]; 

str1 is the required string.
Even if you change MobileSafari to youtube it will work.




回答5:


So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.

NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]]; 

See if tis works for you.



来源:https://stackoverflow.com/questions/7370454/how-to-selectively-trim-an-nsmutablestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!