使用c#在字符数组中插入一个字符串 [英] Insert a string inside a character array using c#

查看:207
本文介绍了使用c#在字符数组中插入一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,



I am having a string as,

string strString = "1 I am good and 2 how are you"





我在字符数组中处理了上面的字符串,如下所示,





I processed the above string in character array as below,

Char[] charReader = new Char[strString .ToCharArray()];





在上面的字符数组中,我包含一个字符串,因为我一直在插入一个字符串,这是一个字符串,



预期o / p应为1 htmltag我很好,2个htmltag你好吗





In the above character array, i am including a string as, were ever the number present i am inserting a string along with it,

expected o/p should be 1 htmltag I am good and 2 htmltag how are you

string strInclude = "htmltag";
Char[] charInclude = new Char[strInclude.ToCharArray()];    





如何插入或序列化字符以插入数字旁边的字符串



How to insert or serialize the characters to insert a string next to number

推荐答案

这很复杂,因为你不想去角色数组附近做任何事情:对于插入而言,它们比字符串更难处理!



从识别标记位置开始插入点 - 在这种情况下是数字。

正如简单的正则表达式将为您做的那样:

That's complicated, because you don't want to go anywhere near character arrays to do this: they are harder to work with for inserts than strings are!

Start with identifyign teh location of your "insert points" - in this case the numbers.
As simple regex will do that for you:
\d+\s



Rexex Match包括索引属性 [ ^ ]告诉你它在字符串中的哪个位置找到了这个数字。

然后,您可以将该索引与string.Substring方法一起使用将字符串分成两部分,并从部分构建一个新字符串:


The Rexex Match includes the Index property[^] which tells you where in the string it found the number.
You can then use the index with the string.Substring method to break the string in two, and build a new one from the parts:

string old = "Abcd";
int index = 2;
string new = old.Substring(0, index) + "xx" + old.Substring(index);

会给你一个包含Abxxcd的新字符串。



您可能希望从最后一场比赛向后工作......

Will give you a new string containing "Abxxcd".

You will probably want to work from the last match backwards...


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string strString = "1 I am good and 2 how are you";

            Char[] charReader =strString.ToCharArray();

            Console.WriteLine();

            string strInclude = "htmltag";

            Char[] charInclude =strInclude.ToCharArray();

            foreach (char ch in charReader)
            {
                if (char.IsNumber(ch) == true)
                {
                    Console.Write(ch+" "+ strInclude);
                }
                else
                   Console.Write(ch.ToString());
            }
            Console.ReadLine();
        }
    }
}


这篇关于使用c#在字符数组中插入一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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