我尝试用单循环编写用于反转字符串中每个单词的逻辑,但我没有让它工作。你能否提供逻辑来使用单循环反转字符串中的每个单词而不使用反向函数。
输入:
欢迎来到世界
输出:
emocleW ot eht dlrow
我的逻辑有两个循环:
class Program
{
static void Main(string[] args)
{
string input = string.Empty;
input = Console.ReadLine();
string[] strarr=input.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string str in strarr)
{
sb.Append(fnReverse(str));
sb.Append(' ');
}
Console.WriteLine(sb);
Console.Read();
}
public static string fnReverse(string str)
{
string result = string.Empty;
for (int i = str.Length-1; i >= 0; i--)
result += str[i];
return result;
}
}
答案 0 :(得分:2)
string strIn = "Welcome to the world";
string strTmp = "";
string strOut = "";
for (int i=strIn.Length-1; i>-1; i--)
{
if (strIn[i] == ' ')
{
strOut = strTmp + " " + strOut;
strTmp = "";
}
else
{
strTmp += strIn[i];
}
}
strOut = strTmp + " " + strOut;
给出结果" emocleW ot ett dlrow"
答案 1 :(得分:1)
string input = Console.ReadLine();
string result = "";
string tmp = "";
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
以下是 DEMO