Par*_*ban 5 .net c# string console-application
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);
Run Code Online (Sandbox Code Playgroud)
在这里,我将字符串分成两个字符串.例如,输入:
你好,世界
输出:
你好,世界.
但现在我需要输出:
dlrow olleH
问题很模糊.如果您需要以相反的顺序将所有单词放在字符串中,例如
"这是一个测试字符串" - >"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);
Run Code Online (Sandbox Code Playgroud)
这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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果你不注意案例,即
"这是一个测试字符串" - >"字符串测试a是这个"
你可以简化解决方案
String source = "This is a test string";
String result = String.Join(" ", source
.Split(' ')
.Reverse());
// "string test a is This"
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
编辑2:如果要将文本拆分为长度相等的range块(可能除了最后一个块),然后反转它们:
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);
Run Code Online (Sandbox Code Playgroud)