c# - 使用 while 将字符串拆分为两个单词

标签 c# .net 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);

这里我将字符串拆分为两个字符串。 例如输入:

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/

相关文章:

javascript - 只保留 A-Z 0-9 并使用 javascript 从字符串中删除其他字符

c# - Excel 中的错误消息

c# - 继承 .net 类

.net - 使用 REGEX 查找 HTML ListItem (.NET) 的内容

java - String[] 到单个字符串

java - 十六进制字符串到int数组的转换

c# - 绑定(bind)复选框列表

c# - WebInvoke 方法 = *

c# - 格式化小数 xamarin

c# - Convert.ToDouble() 抛出格式异常