我的问题很简单。我在 xcode 中为字符串变量赋值,如下所示:
ARAMAUBEBABRBGCNDKDEEEFO,我需要这样的:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO 每个变量的长度不同。
提前谢谢
此功能对于需要每千次昏迷的数字很有用……这就是我想要的,希望对您有所帮助。
//add comas to a a string...
//example1: @"5123" = @"5,123"
//example2: @"123" = @"123"
//example3: @"123123123" = @"123,123,123"
-(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{
NSMutableString *stringFormatted = [NSMutableString stringWithFormat:@"%@",myString];
for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) {
if (i>0) {
[stringFormatted insertString: @"," atIndex: i];
}
}
return stringFormatted;
}
NSString *yourString; // the string you want to process
int len = 2; // the length
NSMutableString *str = [NSMutableString string];
int i = 0;
for (; i < [yourString length]; i+=len) {
NSRange range = NSMakeRange(i, len);
[str appendString:[yourString substringWithRange:range]];
[str appendString:@","];
}
if (i < [str length]-1) { // add remain part
[str appendString:[yourString substringFromIndex:i]];
}
// str now is what your want
尝试这个:
int num;
NSMutableString *string1 = [NSMutableString stringWithString: @"1234567890"];
num = [string1 length];
for(int i=3;i<=num+1;i++) {
[string1 insertString: @"," atIndex: i];
i+=3;
}
当您的字符串不是很大时,这会很好用:
NSString * StringByInsertingStringEveryNCharacters(NSString * const pString,
NSString * const pStringToInsert,
const size_t n) {
NSMutableString * const s = pString.mutableCopy;
for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) {
[s insertString:pStringToInsert atIndex:pos];
}
return s.copy;
}
如果字符串非常大,您应该倾向于在不插入的情况下组合它(仅附加)。
(定义您自己的错误检测)