有一个面试问题,要求我用C#中的下一个单词附上单词的每个最后一个字母。例如,输入是"嘿,你好世界"输出应该是"他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);
答案 0 :(得分:2)
如何使用正则表达式
var newtext = Regex.Replace("Hey hello world", @"(.) "," $1");
答案 1 :(得分:0)
您不必要地使代码复杂化。只需用以前的字符替换空格。
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);
答案 2 :(得分:0)
这是一个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
上试用
答案 3 :(得分:-1)
创建一个空字符串。这将是输出。 然后循环遍历原始字符串,并根据下一个字符将字符附加到输出字符串。
static void Main()
{
string inputString = "Hey Hello World";
string sout = "";//the empty string
int i = 0;//indexer available outside of the for loop
for (; i < inputString.Length - 2; ++i)
if (inputString[i + 1] == ' ')//next character is space
{
sout += ' ';
sout += inputString[i];
++i;//because we forwarded 2 places
}
else
{
sout += inputString[i];
}
sout += inputString[i];//the leftover
if (i + 1 < inputString.Length)
sout += inputString[i + 1];//if the last word was only 1 character long than we append it too
Console.WriteLine(sout);
Console.ReadKey();
}