如何在字符串数组中插入元素 [英] How do I insert elements in a string array
本文介绍了如何在字符串数组中插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在特定字符串之前在字符串数组中插入一个元素。
Ram
ravi
Teja
Vikram
在上面的字符串数组中,我想在Teja之前添加Kumar。
编译应该问我在哪里插入,并且字符串应该插入到所需的索引中。
这里我的代码:
I want to insert an element in string array before a particular string.
Ram
ravi
Teja
Vikram
Here in the above string array I want to add Kumar before Teja.
Compile should ask me where to insert and the string should be inserted in the required index.
Here my code:
Console.Write("Enter the size of the array: ");
string inputSize = Console.ReadLine();
int stringSize;
int.TryParse(inputSize, out stringSize);
string[] stringArray=new string[stringSize];
for (int index = 0; index < stringSize; index++)
{
stringArray[index] = Console.ReadLine();
}
foreach (string strings in stringArray)
{
Console.WriteLine(strings);
}
Console.ReadLine();
推荐答案
您可能需要为此编写函数,例如
You may required to write function for this like
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;
}
这篇关于如何在字符串数组中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文