【问题标题】:How to convert XML based String value to integer in Objective C如何在Objective C中将基于XML的字符串值转换为整数
【发布时间】:2012-11-05 01:26:01
【问题描述】:

这是用逗号分隔的 XML 代码,我将其解析为字符串,现在需要转换为整数: .h 文件中的结构: NSString * 位置;

XML 文件: 100,280,924,320

代码如下:

 NSArray * positons = [partyMember elementsForName:@"position"];
    if (positons.count > 0) {
        GDataXMLElement *firstName = (GDataXMLElement *) [positons objectAtIndex:0];
        //parsed[i].positons = firstName.stringValue;
        parsed[i].positons = firstName.stringValue;
        NSLog(@"position-%@,\n",parsed[i].positons);

名字是本地声明的,parsed[i].positions 有 da 解析值,

【问题讨论】:

  • nslog 打印什么?是这样吗position-100position-280position-924
  • 现在它只打印第一个位置,即 100

标签: objective-c ios xcode4.2 xcode4.3


【解决方案1】:

您可以使用以下方法获取字符串数组:

NSArray* arr = [fullStr componentsSeparatedByString:@","] 

然后从中获取一个 int

int firstInt = [[arr objectAtIndex:0] intValue]; 

【讨论】:

  • @daveGot 非常感谢! :)
【解决方案2】:

您可以使用以下代码从字符串中获取整数值:

  1. 首先获取任何数组中逗号分隔的对象,如下所示:

    NSArray *arrObjects=[parsed[i].positons componentsSeparatedByString:@","]; 
    
  2. 然后使用该数组将字符串值转换为整数,如下所示:

    int iFirstValue=[[arrObjects objectAtIndex:0] intValue];
    

其他人也类似。

【讨论】:

  • @Pedro,@svrushal 这正是我所做的!! :) 非常感谢大家
  • @Dr.Droid:我只是稍微改进了答案的格式。所有的赞美都应该去@svrushal!如果你喜欢这个答案,除了接受它之外,你还可以投票赞成它。
【解决方案3】:

您可以通过以下方式将 NSString 更改为 int 值:

[string intValue];
[string floatValue];

但这只有在值为数字但为字符串形式时才有意义,

【讨论】:

    【解决方案4】:

    这就是我所做的 :) 在视图控制器中应用 Objectatindex 值时更改它

     NSArray * positons = [partyMember elementsForName:@"position"];
        if (positons.count > 0) {
            GDataXMLElement *firstName = (GDataXMLElement *) [positons objectAtIndex:0];
            //parsed[i].positons = firstName.stringValue;
            parsed[i].positons = firstName.stringValue;
            NSLog(@" parsed position is %d, i = %d\n",[parsed[i].positons integerValue],i);
            NSArray* arr = [parsed[i].positons componentsSeparatedByString:@","];
           // firstStr = [[arr objectAtIndex:0] intValue];
            NSLog(@"position-%d,\n",[[arr objectAtIndex:2] intValue]);
    

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 2011-06-04
      • 1970-01-01
      • 2011-01-21
      • 2010-10-30
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      相关资源
      最近更新 更多