2

我正在尝试复制字符串中每个单词的最后一个字符,然后将复制的字符放在下一个单词的第一个位置。例如,如果我输入字符串“The quick brown fox jumps over the lazy dog”,输出应该是“The equick kbrown nfox xjumps sover rthe elazy ydog”;

这是我到目前为止所拥有的:

string s = "The quick brown fox jumps over the lazy dog";

for (int a = 0; a < s.Length; a++)
{
    string b = s.Substring(a,1);
    if (b == " ")
    {
        string c = s.Substring(a - 1, 1);
        string d = s.Insert (a+1, c);
        Console.Write(d);                     
    }                
}

结果是这样的: 敏捷的棕色狐狸跳过懒惰的狗 敏捷的棕色狐狸跳过懒惰的狗 敏捷的棕色 nfox 跳过了懒惰的狗 敏捷的棕色狐狸 x 跳过了懒惰的狗 敏捷的棕色狐狸跳过了懒惰的狗棕色狐狸跳过懒惰的狗快速的棕色狐狸跳过懒惰的狗快速的棕色狐狸跳过懒惰的狗

我想要实现的是这个输出“The equick kbrown nfox xjumps sover rthe elazy ydog”

感谢所有顺便回答的人:)

4

6 回答 6

2

也许:

string[] words = "The quick brown fox jumps over the lazy dog".Split();
string res = String.Join(" ", words.Select((w, i) => i == 0 ? w : words[i-1].Last() + w));

演示

The equick kbrown nfox xjumps sover rthe elazy ydog
于 2013-02-06T10:59:57.273 回答
0

您创建一个新字符串 ( d),在其中插入一个字符,打印它并忘记它。

你可以做什么:

  • 将字符串拆分为单词
  • 换个词
  • 将它们组合成一个新字符串
于 2013-02-06T10:59:01.893 回答
0
var words = s.Split(' ').Where(x=>x!="").ToArray();
var str = "";
var sb = new StringBuilder();
for(var i = 0; i< words.Lenght;i++)
{
    sb.Append(str);
    sb.Append(words[i]);
    sb.Append(" ");
    str = words[words.Lenght - 1].ToString();
}

var result = sb.ToString();
于 2013-02-06T11:00:27.303 回答
0

答案相对简单,您可以使用拆分字符串

string[] sArray = s.Split(new char[]{' '});

然后遍历数组

for (int i = 1; i < sArray.Length; i++)
{
    sArray[i] = sArray[i - 1].Substring(sArray[i - 1].Length) + sArray[i];
}
s = string.Join(" ", sArray);
于 2013-02-06T11:01:00.750 回答
0

应该看起来像这样。

string S= "The quick brown fox jumps over the lazy dog";
                var splitString = S.Split(' ');
                string newS = splitString[0];
                for(int i=1;i<splitString.Length;i++)
                {
                    splitString[i] = splitString[0].ElementAt(splitString[0].Length) + splitString[i];
                    newS += " " + splitString[i];
                }
                Console.WriteLine(newS);
于 2013-02-06T11:02:21.717 回答
0

那这个呢?

string s = "The quick brown fox jumps over the lazy dog";

char lastChar = default(char);
bool addLastChar = false;
var stringBuilder = new StringBuilder(s);
for (int i = 0; i < stringBuilder.Length; i++)
{
    var ch = stringBuilder[i];

    // TODO: consider using char.IsWhiteSpace(ch) method call.
    // Please note: it will return true for different whitespace characters (tabulation, line feed, carriage return, etc).
    if (ch == ' ')
    {
        addLastChar = true;
    }
    else
    {
        if (addLastChar)
        {
            stringBuilder.Insert(i, lastChar);
            addLastChar = false;
        }

        lastChar = ch;
    }
}

var result = stringBuilder.ToString();

该代码也适用于中间有多个空格的字符串,如下所示:

string s = "The    quick    brown   fox jumps over the lazy dog";
于 2013-02-06T11:05:58.193 回答