将字符串转换为int []

时间:2016-05-31 07:29:02

标签: c# arrays string numbers int

我想知道如何将字符串值中的数字转换为int[]。 我将以下数字存储在一个字符串中:

1,2,3,4

但我想知道如何将这些数字存储在int[]中,以便将每个值存储到int数组中。

5 个答案:

答案 0 :(得分:12)

试试这个:

string str = "1,2,3,4";
int[] array = str.Split(',').Select(x => int.Parse(x)).ToArray();

如果你有可能有一个带双逗号的字符串(例如:1,,2,3,4),那么根据@Callum Linington的评论,这将更好用:

int[] array = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
                 .Select(int.Parse)
                 .ToArray();

上面的代码是什么:

  1. 在调用Split()后创建一个字符串数组,因此在该方法调用之后,我们将会这样:{ "1", "2", "3", "4"}
  2. 然后我们将每个字符串传递给int.Parse(),这会将它们转换为32位有符号整数。
  3. 我们采用所有这些整数,并使用ToArray()
  4. 从中创建一个数组

答案 1 :(得分:6)

使用Linq:

convertView.setOnclickListener()

使用method group

可能更简单
public class CustomListItemsAdapter extends BaseAdapter{

private Context context;
private int selectedNetWeightPosition=0; 
private String netWeightValuesPerItem="";

private String[] arrayOfNetWeights;
private String[] arrayOfSelectedNetWeights;

private LayoutInflater inflater;

public CustomListItemsAdapter(ListItemsActivity listItemsActivity, String[] itemNetWeight, String[] itemNetWeightSelected) {
    // TODO Auto-generated constructor stub

    context=listItemsActivity;
    arrayOfNetWeights = itemNetWeight;
    arrayOfSelectedNetWeights = itemNetWeightSelected;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return arrayOfNames.length;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

public static class ViewHolder
{
    private TextView netWeightText;
    private LinearLayout netWeightLayout;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    final ViewHolder holder;     

    if(convertView==null)
    {
        holder=new ViewHolder();
        convertView = inflater.inflate(R.layout.list_item_content, parent, false);
        holder.netWeightLayout = (LinearLayout) convertView.findViewById(R.id.itemNetWeightLayout);

        String[] data=arrayOfNetWeights[position].split(",");
        for(int j=0;j<data.length;j++)
        {
            holder.netWeightText = new TextView(context);
            LinearLayout.LayoutParams netWeightTextParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            netWeightTextParams.setMargins(0, 0, 20, 0);
            holder.netWeightText.setLayoutParams(netWeightTextParams);
            holder.netWeightText.setPadding(10, 10, 10, 10);
            holder.netWeightText.setId(j);
            holder.netWeightText.setText(data[j]);
            holder.netWeightText.setTag(position);
            holder.netWeightText.setBackgroundResource(R.drawable.netweight_default);
            holder.netWeightText.setTextColor(Color.BLACK);
            if(j==selectedNetWeightPosition)
            {
                holder.netWeightText.setBackgroundResource(R.drawable.netweight_clicked);
            }
            holder.netWeightLayout.addView(holder.netWeightText);
        }
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    OnClickListener netWeightTextListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            String[] data=arrayOfNetWeights[position].split(",");
            for(int i=0;i<data.length;i++)
            {
                int pos = v.getId();
                if(pos!=i)
                {
                    TextView netWeightTextUnClicked = (TextView) holder.netWeightLayout.getChildAt(i);
                    netWeightTextUnClicked.setBackgroundResource(R.drawable.netweight_default);
                }
                else
                {
                    TextView netWeightTextClicked = (TextView) holder.netWeightLayout.getChildAt(pos);
                    netWeightTextClicked.setBackgroundResource(R.drawable.netweight_clicked);
                }
            }   
        }
    };

    String[] data=arrayOfNetWeights[position].split(",");
    for(int j=0;j<data.length;j++)
    {
        holder.netWeightText.setOnClickListener(netWeightTextListener);
    }

    convertView.setOnClickListener(new OnClickListener() {            

        @Override
        public void onClick(View v) {

            Toast.makeText(context, "You Clicked", Toast.LENGTH_LONG).show();
        }
    });   

 return convertView;
 }
}

另外,如果您不了解Linq的更多信息,还有另一种使用Array.ConvertAll方法转换一种类型数组的方法(调用后的字符串数组 { {1}})您想要的另一种类型的数组string str = "1,2,3,4"; var result = str.Split(',').Select(c => Convert.ToInt32(c)).ToArray(); ):

var result = str.Split(',').Select(int.Parse).ToArray();

答案 2 :(得分:1)

bool isInt = true;
string[] str = "1,2,3,4".Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
int counter = 0;
List<int> parsedInts = new List<int>(str.Length);

while(isInt && counter < str.Length)
{
    int parsedInt;
    isInt = int.TryParse(str[counter], out parsedInt);
    counter++;
    if (isInt) {
        parsedInts.Add(parsedInt);
    }
}

// then you can return the list as an array if you want
parsedInts.ToArray();

虽然这个方法更长更冗长,但实际上确保你可以在将字符串分配给数组之前将其解析为int。

请务必在此处注意,一旦无法解析字符串,它就会被取消,但是如果您遇到错误的数据类型,我们非常欢迎您加入else

答案 3 :(得分:0)

你可以使用,

ACCESS_FINE_LOCATION

答案 4 :(得分:0)

Int32.Parse(stringname)

或者

Int32.TryParse(stringname,out outputvariable)

如果以逗号分隔,则首先将它们分开stringname.split(','),这将返回字符串数组并使用while循环单独解析它们。