string givenstring,outputString="";
int i, j = 0;
Console.WriteLine("Enter the string");
givenstring = Console.ReadLine();
i = (givenstring.Length) / 2;
while (j < i)
{
outputString += givenstring[j];
j++;
}
Console.WriteLine(outputString);
outputString = string.Empty;
while (i < givenstring.Length)
{
outputString += givenstring[i];
i++;
}
Console.WriteLine(outputString);
这里我将字符串拆分为两个字符串。 例如输入:
Helloworld
输出:
Hello world.
但现在我需要输出:
dlrow olleH
最佳答案
这个问题含糊不清。如果您需要将字符串中的所有单词 倒序,例如
"This is a test string" -> "String test a is this"
然后你可以做
String source = "This is a test string";
String result = String.Join(" ", source
.Split(' ')
.Reverse()
.Select((item, index) => index > 0 ? item.ToLower() : ToNameCase(item)));
// "String test a is this"
Console.WriteLine(result);
ToNameCase()
是这样的:
private static String ToNameCase(String source) {
if (String.IsNullOrEmpty(source))
return source;
StringBuilder sb = new StringBuilder(source.Length);
sb.Append(Char.ToUpper(source[0]));
sb.Append(source.Substring(1));
return sb.ToString();
}
编辑:如果你不注意大小写,即
"This is a test string" -> "string test a is This"
您可以将解决方案简化为
String source = "This is a test string";
String result = String.Join(" ", source
.Split(' ')
.Reverse());
// "string test a is This"
Console.WriteLine(result);
编辑 2:如果您想将文本拆分为 range
个等长的 block (最后一个可能异常(exception) block ),然后反转它们:
String source = "HelloWorld";
int range = 2; // we want 2 chunks ("Hello" and "World")
String result = String.Join(" ", Enumerable
.Range(0, range)
.Select(index => index == range - 1 ?
source.Substring(source.Length / range * index) :
source.Substring(source.Length / range * index, source.Length / range))
.Reverse()); // remove ".Reverse()" and you will get "Hello World"
// "World Hello"
Console.WriteLine(result);
关于c# - 使用 while 将字符串拆分为两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495573/