简体   繁体   English

如何将数组的一个值添加到字符串

[英]How to add one value of an array to a string

Basically I have a string array with a few text values in it.基本上我有一个字符串数组,里面有一些文本值。 I want to on load assign a value from the array to a string then on button press change it to the next value, once it gets to the end it needs to loop around.我想在加载时将数组中的一个值分配给一个字符串,然后按下按钮将其更改为下一个值,一旦它到达末尾,它需要循环。 So the string will be set to one value in the array then get changed after a button click.因此,字符串将被设置为数组中的一个值,然后在单击按钮后更改。

        Array stringArray = Array.CreateInstance(typeof(String), 3);
        stringArray.SetValue("ssstring", 0);
        stringArray.SetValue("sstring", 1);
        stringArray.SetValue("string", 2);

Here's some code to get you going.这里有一些代码可以帮助你。 You dont mention what environment you're using (ASP.NET, Winforms etc..)您没有提及您正在使用什么环境(ASP.NET、Winforms 等)

When you provide more info I'll update my example so its more relevant.当您提供更多信息时,我将更新我的示例,使其更具相关性。

public class AClass
{
    private int index = 0;
    private string[] values = new string[] { "a", "b", "c" };

    public void Load()
    {
        string currentValue = this.values[this.index];
    }

    private void Increment()
    {
        this.index++;

        if (this.index > this.values.Length - 1)
            this.index = 0;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Increment();
    }
}

Set Index = 0设置索引 = 0

Let Count = StringArray.Count让 Count = StringArray.Count

On Button Click Do the following在按钮上单击执行以下操作

Set Return Value As StringArray(Index)
Set Index =  ( Index + 1 ) Mod Count

You can program that algorithm in C#...您可以在 C# 中对该算法进行编程...

You could have a class that holds and iterates your strings like:您可以拥有一个 class 来保存和迭代您的字符串,例如:

class StringIterator
{
    private int _index = 0;
    private string[] _strings;        

    public StringIterator(string[] strings) 
    {
        _string = strings;
    }

    public string GetString()
    {
        string result = _string[_index];
        _index = (_index + 1) % _strings.Length;
        return result;
    }
}

The usage would look like用法看起来像

class Program
{
    private string _theStringYouWantToSet;
    private StringIterator _stringIter;

    public Program()
    {
        string[] stringsToLoad = { "a", "b", "c" };
        _stringIter = new StringIterator(stringsToLoad);
        _theStringYouWantToSet = _stringIter.GetString();
    }        

    protected void ButtonClickHandler(object sender, EventArgs e)
    {
        _theStringYouWantToSet = _stringIter.GetString();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM