简体   繁体   English

替换字符串中的单个字符

[英]Replace single character in a String

So, I'm using unity and I have this string that contains the current state of a tic-tac-toe board. 因此,我正在使用unity,并且我有一个包含井字游戏板当前状态的字符串。 It looks like that: 看起来像这样:

XOX
ONX
OXX

"N" being a neutral space. “ N”是一个中性空间。

The thing is I want to replace one of those "N" with either an "X" or an "O". 问题是我想用“ X”或“ O”代替那些“ N”。 I tried using : 我尝试使用:

board[n] = "X";

but i get 但我明白了

"property or indexer cannot be assigned, it is read only" “无法分配属性或索引器,它是只读的”

So I'm trying to figure a way to change one of those "N". 因此,我试图找到一种方法来更改其中一个“ N”。 Here is my code 这是我的代码

if (manager.turn == 1 && !isUsed)
{
    xSprite.enabled = true;
    manager.board[int.Parse(gameObject.name)-1] = 'X';
    manager.GameEndingDraw();
    isUsed = true;
    manager.turn = 2;
}
else if (manager.turn == 2 && !isUsed)
{
    oSprite.enabled = true;
    manager.board[int.Parse(gameObject.name)-1] = 'O';
    manager.GameEndingDraw();
    isUsed = true;
    manager.turn = 1;
}

A Tic-Tac-Toe board is not a string, it is a 3×3 grid of markers such as chars. 井字游戏板不是字符串,而是3×3的标记网格,例如字符。 You should represent it as an array, not a string: 您应该将其表示为数组,而不是字符串:

var board = new char[3, 3];
for (int i = 0; i < board.GetLength(0); i++)
    for (int j = 0; j < board.GetLength(1); j++)
        board[i, j] = 'N';

Then you can set each marker by its coordinates: 然后,您可以通过其坐标设置每个标记:

board[0, 0] = 'X';

Here are 4 methods you can use: 您可以使用以下4种方法:

ToCharArray ToCharArray

var array = board.ToCharArray();
array[indexOfNew] = newChar;
board = new string(array);

StringBuilder StringBuilder

var sb = new StringBuilder(board);
sb[indexOfNew] = newChar;
board = sb.ToString();

String.Remove and String.Insert String.Remove和String.Insert

board = board.Remove(indexOfNew, 1)
    .Insert(indexOfNew, newChar.ToString());

SubString and String Interpolation 子字符串和字符串插值

board = $"{board.Substring(0, indexOfNew)}{newChar}{board.Substring(indexOfNew+1, board.Length-indexOfNew-1)}";

Assuming board contains the original string, newChar contains the newly placed "piece" and indexOfNew contains the index in the string which you need to replace. 假设board包含原始字符串, newChar包含新放置的“作品”和indexOfNew包含你需要替换字符串中的索引。

And you could of course wrap the option you choose in an extension method: 当然,您可以将选择的选项包装在扩展方法中:

public static string ReplaceAt(this string inputString, int newCharIndex, char newChar)
{
    var newString = // Insert your choice of replacement from above here
    return newString;
}

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

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