[英]Attach every last letter of the word with the next word in C#
There is an interview question that asks me to attach every last letter of the word with the next word in C#.有一个面试问题要求我在 C# 中将单词的每个最后一个字母与下一个单词相连。 For example the input is "Hey hello world" and the output should be "He yhell oworld".
例如,输入是“Hey hello world”,输出应该是“He yhell oworld”。
I've come up with the code below but is there a better way to do this?我想出了下面的代码,但有没有更好的方法来做到这一点? Perhaps in LINQ?
也许在 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");
You are unnecessarily complicating the code.您不必要地使代码复杂化。 Simply replace space with previous character.
只需用前一个字符替换空格。
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);
Here's a LINQ solution, since that seems to be what the OP is looking for.这是一个 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);
}
}
Output:输出:
He yhell oworld
Try it out on DotNetFiddle在DotNetFiddle上试试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.