如何将字符循环回字符串 [英] How Do I loop Characters back into a string

查看:65
本文介绍了如何将字符循环回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个活动工作委员会,并且已经完成了制作一些Anagrams的任务。我已经制作了一个应用程序,它将一个字符串循环出空格并制作AN字谜。同时,该应用程序记录了每个角色的空间被取出的点。我现在需要在空格中循环回到空间中的列表或数组?所以我有一些手动更改,所以我完成了我的任务,但没有完成我的任务的程序标准。



示例



诅咒女王



阵列空间位置(5,11,14,18)。



我在列表中有十个数组



这样的东西



'eaeudhftnnmeedetqoh'我希望在5,11,14和18点放一个空格?



我试过一个二维阵列它适用于第一个空间,但之后没有。我可以根据可能的10个空格进行硬编码,但这对于所有情况的99.9999999%都足够了,但它确实在.0000001%次突破!

I am on a work committee for activities and have been give the task of making some Anagrams. I have made and app that takes a string loops out the spaces and makes AN anagram. Concurrently, the app made note of the point at which each character the space was taken out. I now need to loop back in the spaces into a list or an array at the point of the space? So I have it to work with some manual alteration, so I have completed my task but not to the standard, of the programme doing the work.

Example

The Queen of the Damned

array space position (5,11,14,18).

I ten have in a List an array

something like this

'eaeudhftnnmeedetqoh' and I wish to put a space in at point 5,11,14 and 18?

I have tried a 2d array and it works for the first space, but none after. I could hard code based on maybe 10 spaces but that would be sufficient for 99.9999999% of all situations, but it did break at that .0000001% times!

推荐答案

As通过 Foothill [ ^ ] ...

As to advice in the solution 1 by Foothill[^]...
string s = "eaeudhftnnmeedetqoh";
int[] spaces = new int[]{5,11,14,18};
StringBuilder sb = new StringBuilder();
int j = 0;
for(int i=0; i<s.Length; i++)
{
    if (i == spaces[j])
    {
        sb.Append(" " + s[i]) ;
        j+=1;
    }
    else
    {
        sb.Append(s[i]);
    }
}
Console.WriteLine(sb.ToString());


假设您对随机化感到满意你的代码创建的字符串(你使用的是Fisher-Yates吗?),然后:

Assuming you are satisfied with the randomized string created by your code (are you using Fisher-Yates ?), then:
// requires Linq
public string InsertSpaces(string source, params int[] insertats)
{
    // make sure inserts are in ascending order
    var sortedparams = insertats.ToList<int>().OrderBy(i => i);
    
    StringBuilder sb = new StringBuilder(source);

    foreach (var i in sortedparams) sb.Insert(i - 2, space);

    return sb.ToString();
}

// sample usage:

public const char space = ' ';

string anagram = "eaeudhftnnmeedetqoh"

string anagramwithspaces = InsertSpaces(anagram, 5,11,14,18);
 
// result: eae udhft nn mee detqoh


您可以尝试使用StringBuilder类而不是arry。
You can try using the StringBuilder class instead of an arry.


这篇关于如何将字符循环回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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