0

私はいくつかのひもを持っています。それらは次のようになります: 1/2 ポンドのステーキ。ここで、文字列を 1/2 で分割し、1/2 を数値に変換する必要があります。文字列にさらに多くのスペースが含まれている可能性があり、1/2 が 1/6 またはその他の数値である可能性もあります。分割して変換する方法を知っている人はいますか?

4

1 に答える 1

1

これで問題は解決するはずです:

NSString *input = @"3/4 pounds of sugar";
// trim white space at the beginning and end
input = [input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// define charater set to split
NSCharacterSet *chSet = [NSCharacterSet characterSetWithCharactersInString:@" /"];
// split string into array of strings by charaters '/' and ' '
NSArray *split = [input componentsSeparatedByCharactersInSet:chSet];
// the result of the fraction inside result
double result = [split[0] doubleValue] / [split[1] doubleValue];
于 2013-09-01T18:51:43.193 に答える