问题
I need to make function that determine longer word of two entered. I have tried to use if-statement and String.Length
, but I can't get it right. What would be the best way to make the function?
Below is the main program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class LongerWord
{
public static void Main(string[] args)
{
Console.Write("Give 1. word >");
String word1 = Console.ReadLine();
Console.Write("Give 2. word >");
String word2 = Console.ReadLine();
String longer = LongerString(word1, word2);
Console.WriteLine("\"" + longer + "\" is longer word");
Console.ReadKey();
}
}
回答1:
that should be a start...of something...
private string LongerString(string x, string y)
{
return x.Length > y.Length ? x : y;
}
回答2:
So I figured out how to do the function properly, thanks for all your help! I had to use return statement. If words were the same length then first word needed to be the displayed one. Here is what I got:
public static string LongerString(string word1 , string word2)
{
if (word1.Length >= word2.Length)
{
return word1;
}
else
{
return word2;
}
}
回答3:
I don't see why using stringName.Length
won't work. Look at this code:
Console.Write("Give 1. word >");
string word1 = Console.ReadLine();
Console.Write("Give 2. word >");
string word2 = Console.ReadLine();
if(word1.Length > word2.Length)
{
Console.Write("String One is longer.");
}
else
{
Console.Write("String Two is longer.");
}
As a function, it would like this:
namespace String_Length
{
class Program
{
static void Main(string[] args)
{
Console.Write("Give 1. word >");
string word1 = Console.ReadLine();
Console.Write("Give 2. word >");
string word2 = Console.ReadLine();
CompareStrings(word1, word2);
Console.ReadKey();
}
static void CompareStrings(string one, string two)
{
if (one.Length > two.Length)
{
Console.Write("String One is longer.");
}
else
{
Console.Write("String Two is longer.");
}
}
}
}
You might also want to add code for if the length of both strings are equal too each other, possibly with a try-catch block. I hope this helps.
来源:https://stackoverflow.com/questions/42057956/comparing-string-lengths-in-c-sharp