Comparing string lengths in C#

2019-09-20 17:01发布

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();
    }
}

3条回答
等我变得足够好
2楼-- · 2019-09-20 17:29

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楼-- · 2019-09-20 17:30

that should be a start...of something...

private string LongerString(string x, string y)
{
    return x.Length > y.Length ? x : y;
}
查看更多
SAY GOODBYE
4楼-- · 2019-09-20 17:31

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.

查看更多
登录 后发表回答