[英]Split and replace string with character
I need to extract the values which are between the special characters &
. 我需要提取特殊字符&
之间的值。
string text = "&2&LL&1&likk&3&";
I need to extract the value 2, 1, 3
and insert the corresponding index of the List<string>
. 我需要提取值2, 1, 3
并插入List<string>
的相应索引。
The list contains 10 elements: 该列表包含10个元素:
0 - A
1 - B
2 - C
3 - D
...
9 - J
Finally when I substitute the list element to the string, it should be printed as C LL B likk D . 最后,当我将list元素替换为字符串时,应将其打印为C LL B likk D。 How can I do this ? 我怎样才能做到这一点 ?
I tried splitting as follow:But, It only splits using the & sign. 我尝试按如下方式进行拆分:但是,它仅使用&符号进行拆分。
string[] xx = text.Split('&');
try this: 尝试这个:
List<string> f = new List<string> ( ) { "A", "B", "C", "D", "E", "F", "G" };
string text = "&2&LL&1&likk&3&";
for ( int i = 0; i < f.Count; i++ )
{
text = text.Replace ( i.ToString ( ), f[ i ] );
}
text=text.Replace ( "&", "" );
Console.WriteLine ( text );
go through all the values in the list with a "FOR" and reasign the value of text with the value to replace 用“ FOR”遍历列表中的所有值,并用替换的值重新分配文本的值
EDITED EDITED
List<string> f = new List<string> ( ) { "A", "B", "C", "D", "E", "F", "G" };
string text = "&2&LL&1&likk&3&";
for ( int i = 0; i < f.Count; i++ )
{
text = text.Replace ($"&{ i.ToString ( )}&", f[ i ] );
}
Console.WriteLine ( text );
正则表达式替代(17与'A' - '0'
的区别):
var result = Regex.Replace("&2&LL&1&likk&3&", "&[0-9]&", m => (char)(m.Value[1] + 17) + "");
Hi you can try something like this 嗨,你可以尝试这样的事情
string text = "&2&LL&1&likk&3&";
string[] xx = text.Split('&');
string text2 = "";
string[] abc = { "A","B","C","D","E","F","G","H","I","J" };
for (int i = 0; i < xx.Length; i++)
{
text2 += xx[i];
}
for (int i = 0; i < abc.Length; i++)
{
text2 = text2.Replace(""+i, abc[i]);
}
MessageBox.Show(text2);
You should use regular expressions to do this, because regex is fun! 您应该使用正则表达式来执行此操作,因为正则表达式很有趣!
&\\d& will match all of the digits between & symbols. &\\ d&将匹配&符号之间的所有数字。 Considering you're implying that letters and numbers should map together, we can adopt Henocs answer to to use regex for bonus points! 考虑到您的意思是字母和数字应该映射在一起,我们可以采用Henocs的答案来使用正则表达式来获得积分!
List<string> f = new List<string> ( ) { "A", "B", "C", "D", "E", "F", "G" };
string text = "&2&LL&1&likk&3&";
for ( int i = 0; i < f.Count; i++ )
{
text = text.RegexReplace ( text, "&" + i + "&", f[ i ] );
}
Console.WriteLine ( text );
By creating a regular expression of &(target digit)&, and replacing it with a letter from our string list, we will replace the entire block, rather than just the number. 通过创建&(目标数字)&的正则表达式,并将其替换为字符串列表中的字母,我们将替换整个块,而不仅仅是数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.