[英]Remove white space from the left of NSString
我只需要從 NSString 的左側刪除空格我的意思是
如果我有" This is a good day"
我將有"This is a good day"
只有左邊的空格
請有任何建議
只需使用
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
它將從左側和右側刪除所有多余的空間,但不會從中間刪除
並刪除空格和\n
使用
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
使用下面從您的NSString
中刪除白色和新行字符。
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Nsstring *str=" This is a good day";
while ([str rangeOfString:@" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
nslog(@"string after removing space %@",)
這是我遇到相同問題時提出的解決方案:
- (NSString*)trimBlankCharactersFromBeginningOfString:(NSString*)originalString
{
//we are only trimming the characters on the left side of the string
NSInteger count = [originalString length];
NSString *trimmedNewText = originalString;
for (int i = 0; i < count; i++) {
if([[originalString substringWithRange:NSMakeRange(i, 1)] rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location == NSNotFound)
{
trimmedNewText = [originalString substringFromIndex:i];
break;
}
else
{
if(i+1 < count)
{
trimmedNewText = [originalString substringFromIndex:i+1];
}
//since we are exiting the loop as soon as a non blank space character is found
//then this is just really checking to see if we are on the last character of an
//all whitespace string. can't say i+1 here because that would give an index out
//of bound exception
else
{
trimmedNewText = @"";
}
}
}
return trimmedNewText;
}
對於僅向左修剪的解決方案是在字符串的右側添加一個虛擬字符,修剪字符串,然后將其刪除。
NSString* tempString = [NSString stringWithFormat@"%@T", yourString];
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return [result substringToIndex:[result length]-1];
只有左邊的空格
while ([[yourString substringToIndex:1] isEqualToString:@" "])
yourString = [yourString substringFromIndex:1];
NSString *str = @" This is a good day";
NSArray *arrString = [str componentsSeparatedByString:@"T"];
NSString *strSpace = [arrString objectAtIndex:0]; // White space
NSString *strString = [arrString objectAtIndex:1]; //This is a good day
然后,您可以將字符串中的 append T作為
NSString *strT = @"T";
strString = [strT stringByAppendingString:strString];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.