How to remove the last word from a string in C#

2 Answers

0 votes
using System;

public class RemoveLastWordProgram
{
    // Removes the last word from a space-separated string.
    public static string RemoveLastWord(string input)
    {
        // Split into words, ignoring extra spaces
        string[] arr = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        // No words → return empty string
        if (arr.Length == 0)
            return "";

        // One word → return original input unchanged
        if (arr.Length == 1)
            return arr[0];

        // Remove the last word
        Array.Resize(ref arr, arr.Length - 1);

        return string.Join(" ", arr);
    }

    public static void Main(string[] args)
    {
        string s = "c# vb.net c c++ java";

        string result = RemoveLastWord(s);
        Console.WriteLine("1. " + result);

        result = RemoveLastWord("");
        Console.WriteLine("2. " + result);

        result = RemoveLastWord("c#");
        Console.WriteLine("3. " + result);

        result = RemoveLastWord("c c++ java ");
        Console.WriteLine("4. " + result);

        result = RemoveLastWord("  ");
        Console.WriteLine("5. " + result);
    }
}

 
 
/*
run:
 
1. c# vb.net c c++
2. 
3. c#
 
*/

 



answered Feb 24, 2017 by avibootz
edited Mar 27 by avibootz
0 votes
using System;
 
public class RemoveLastWordProgram
{
    // Removes the last word from a space-separated string.
    // If there are no words, returns an empty string.
    // If there is only one word, returns that word unchanged.
    public static string RemoveLastWord(string input)
    {
        // Trim trailing spaces so the last "word" is real text
        string trimmed = input.TrimEnd();
 
        // Find the last space in the trimmed string
        int index = trimmed.LastIndexOf(' ');
 
        // No space found:
        // - if trimmed is empty → no words → return empty string
        // - otherwise → single word → return it unchanged
        if (index == -1)
            return trimmed;
 
        // Return everything before the last space
        return trimmed.Substring(0, index);
    }
 
    public static void Main(string[] args)
    {
        string s = "c# vb.net c c++ java";
 
        string result = RemoveLastWord(s);
        Console.WriteLine("1. " + result);
 
        result = RemoveLastWord("");
        Console.WriteLine("2. " + result);
 
        result = RemoveLastWord("c#");
        Console.WriteLine("3. " + result);
 
        result = RemoveLastWord("c c++ java ");
        Console.WriteLine("4. " + result);
 
        result = RemoveLastWord("  ");
        Console.WriteLine("5. " + result);
    }
}

  
  
/*
run:
  
1. c# vb.net c c++
2. 
3. c#
4. c c++
5. 
  
*/

 



answered Sep 24, 2025 by avibootz
edited Mar 27 by avibootz
...