简体   繁体   中英

c# how do i cut a string with a random length in half?

i am trying to learn programming by doing some simple exercises online. and after searching i couldn't find a answer.

Problem:

    public static void Main(string[] args)
    {
        // get sentence
        Console.WriteLine("type a sentence: ");
        string Sentence = Console.ReadLine();

        // insert code for cutting sentence in half

        // display first half of the sentence
        Console.Write(firstHalf);
        Console.WriteLine();
    }
}

thanks in advance !

You can use the String.Substring method for that.

string firsthalf = Sentence.Substring(0, Sentence.Length/2);

The first parameter 0 is the starting point of the substring and the second denotes how many characters the substring should include.

The String.Length property helps you to determine the length of the string.

Important note:

When you divide the length by 2 you need to know that it is an integer division! That means that 3/2 = 1 and 1/2 = 0 so if your string is only 1 character long you will be an empty string as the first half;) and if it is 3 letters long you get only the first letter.

Good fortune with the learning:)

You can get the length of the string using the Length property and use Substring to take half of the string

 firstHalf = s.Substring(0, s.Length / 2)

You can use the range operator .. :

var firstHalf = sentence[..(sentence.Length / 2)];

source

You can use Remove :

var firstHalf = sentence.Remove(sentence.Length/2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM