如何将元素插入到字符串数组中 [英] How to insert elements into string array

查看:88
本文介绍了如何将元素插入到字符串数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在数组中插入元素。



例如



s [0] = Ram

s [1] =Ravi

s [2] =詹姆斯

s [3] =雅各布

s [4] =Abdul





这里我想在詹姆斯之前插入一个新的字符串。 />


用户输入应该是James。



自动应该在James之前插入。

I need to insert element in an array.

For example

s[0]="Ram"
s[1]="Ravi"
s[2]="James"
s[3]="Jacob"
s[4]="Abdul"


Here I want to insert a new string before James.

The User Input should be James.

Automatically it should be inserted before James.

推荐答案

首先获取James的索引,在该位置添加元素并将所有其他索引增加1.

First get the index of "James", add element at that position and increment all other indexes by 1.
string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }

    result result;
}



参考: stackoverflow [ ^ ]



-KR


reference : stackoverflow[^]

-KR


这篇关于如何将元素插入到字符串数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆