簡體   English   中英

將單詞的每個最后一個字母與 C# 中的下一個單詞相連

[英]Attach every last letter of the word with the next word in C#

有一個面試問題要求我在 C# 中將單詞的每個最后一個字母與下一個單詞相連。 例如,輸入是“Hey hello world”,輸出應該是“He yhell oworld”。

我想出了下面的代碼,但有沒有更好的方法來做到這一點? 也許在 LINQ 中?

string inputString = "Hey Hello World";
string[] stringArray = inputString.Split(' ').ToArray();
StringBuilder resultString = new StringBuilder("");
StringBuilder lastLetter = new StringBuilder(""); 

for (int i = 0; i < stringArray.Length; i++)
{
    string temp = stringArray[i].ToString();

    if (i < stringArray.Length - 2)
    {
        resultString.Append(lastLetter + temp.Substring(0, temp.Length - 1));
        lastLetter.Clear();
        lastLetter.Append(" " + temp.Substring(temp.Length - 1, 1));
    }
    else
        resultString.Append(lastLetter + temp.Substring(0, temp.Length));
}

Console.WriteLine(resultString);

如何使用正則表達式

var newtext = Regex.Replace("Hey hello world", @"(.) "," $1");

您不必要地使代碼復雜化。 只需用前一個字符替換空格。

        var input = "Hey Hello world";
        var arr = input.Trim().ToCharArray();
        for(int i =0; i< arr.Length; i++)
        {
            if(arr[i]==' ')
            {
                var temp = arr[i];
                arr[i] = arr[i - 1];
                arr[i - 1] = temp;
            }
        }
        Console.WriteLine(arr);

這是一個 LINQ 解決方案,因為這似乎是 OP 正在尋找的。

using System;
using System.Linq;

public class Program
{
    const char space = ' ';

    public static string DoHomework(string input)
    {
        return new string
        (
            input.Select( (c,i) => 
            {
                if (i == 0 || i == input.Length-1) return c;
                if (c == space) return input[i-1];
                if (input[i+1] == space) return space;
                return c;
            }).ToArray()    
        );
    }

    public static void Main()
    {
        var input = "Hey hello world";
        var output = DoHomework(input);

        Console.WriteLine(output);
    }
}

輸出:

He yhell oworld

DotNetFiddle試試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM