IRONSOFTWAREHOME
.NET HELP

C# Get Last Character of String (How It Works)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: July 19, 2026

In C#, string manipulation is an essential skill, whether you're processing data from user inputs, filenames, or generating dynamic content for reports. One common task is extracting specific parts of a string, such as the last character, for further processing.

When working with tools like IronPDF, which allows developers to generate PDFs dynamically from string or HTML data, mastering string manipulation becomes even more valuable. In this article, we'll explore how to extract the last character from a string in C# and integrate that knowledge with IronPDF to create powerful, dynamic PDFs.

Understanding String Manipulation in C#

Common Scenarios for Working with Strings

String manipulation is a core aspect of many programming tasks. Here are a few common scenarios where string processing is crucial:

  • Data Processing: Extracting specific portions of strings, such as file extensions or unique identifiers from user inputs.
  • Report Generation: Formatting and processing string data to dynamically generate reports.
  • Validation and Filtering: Using string methods to validate inputs, extract patterns, or categorize data.

For example, let's say you are generating a report from a list of usernames or product codes, and you need to group or categorize these based on their last characters. This is where extracting the last character of a string comes in handy.

Basic C# Get Last Character of String Methods

In C#, strings are zero-indexed arrays of characters, which means the first character is at index 0, and the last character is at index string.Length - 1. Here are a few methods to extract the last character of a string:

Using Substring()

The Substring() method allows you to extract parts of a string based on index positions. Here's how to use it to get the last character of a string:

// Original string
string myString = "Example";
// Retrieving the last character from the string
char lastChar = myString.Substring(myString.Length - 1, 1)[0];
Console.WriteLine(lastChar); // Output: 'e'

Using Array Indexing

Another approach is to access the specified character position directly using array indexing:

string input = "Example";
char outputChar = input[input.Length - 1];
Console.WriteLine(outputChar); // Output: 'e'

Using ^1 (C# 8.0 and Above)

The ^ operator provides a more concise way to access elements from the end of an array or string. The ^1 indicates the last character:

string input = "Example";
char lastChar = input[^1];
Console.WriteLine(lastChar); // Output: 'e'

Example: Extracting the Last Character from Strings for PDF Generation

Let's apply this string manipulation in a real-world scenario. Suppose you have a list of product codes, and you want to extract the last character from each code and use it in a PDF report.

List<string> productCodes = new List<string> { "ABC123", "DEF456", "GHI789" };
foreach (var code in productCodes)
{
    char lastChar = code[^1];
    Console.WriteLine($"Product code: {code}, Last character: {lastChar}");
}

Using String Data with IronPDF for PDF Generation

Setting Up IronPDF in Your .NET Project

To start using IronPDF, you will first need to install it. If it's already installed, then you can skip to the next section. Otherwise, the following steps cover how to install the IronPDF library.

Via the NuGet Package Manager Console

To install IronPDF using the NuGet Package Manager Console, open Visual Studio and navigate to the Package Manager Console. Then run the following command:

PM > Install-Package IronPdf

Via the NuGet Package Manager for Solution

Open Visual Studio, go to "Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution" and search for IronPDF. From here, select your project and click "Install", and IronPDF will be added to your project.

Once you have installed IronPDF, you need to add the following using statement at the top of your code to start using IronPDF:

using IronPdf;

Generating a PDF from Extracted String Data

Now that we've extracted the last character from each product code, let's create a PDF report that includes these characters. Here's a basic example:

using IronPdf;
List<string> productCodes = new List<string> { "ABC123", "DEF456", "GHI789" };
ChromePdfRenderer renderer = new ChromePdfRenderer();
string htmlContent = "<h1>Product Report</h1><ul>";
foreach (var code in productCodes)
{
    char lastChar = code[^1];
    htmlContent += $"<li>Product code: {code}, Last character: {lastChar}</li>";
}
htmlContent += "</ul>";
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("ProductReport.pdf");

This code generates a PDF report that lists each product code and its last character, making it easy to categorize or analyze. It uses the ChromePdfRenderer and PdfDocument classes to render the HTML content into a PDF document. This HTML content is created dynamically using the data stored in our list.

Advanced String Manipulation Techniques for PDF Generation

Using Regular Expressions for Complex String Operations

For more complex string operations, such as finding patterns or filtering data based on specific criteria, regular expressions (regex) come in handy. For instance, you might want to find all product codes ending with a digit:

using IronPdf;
using System.Text.RegularExpressions;
class Program
{
    public static void Main(string[] args)
    {
        List<string> productCodes = new List<string> { "ABC123", "DEF456", "GHI789", "GJM88J" };
        Regex regex = new Regex(@"\d$");
        foreach (var code in productCodes)
        {
            if (regex.IsMatch(code))
            {
                string htmlContent = $@"
<h1>Stock Code {code}</h1>
<p>As an example, you could print out inventory reports based off the codes you have stored.</p>
<p>This batch of PDFs would be grouped if all the codes ended with a digit.</p>
";
                ChromePdfRenderer renderer = new ChromePdfRenderer();
                PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
                pdf.SaveAs($"code_{code}.pdf");
                Console.WriteLine($"Product code: {code} ends with a digit.");
            }
        }
    }
}

In this code example, we first create a List of product codes, initialized with sample string values like "ABC123", "DEF456", etc. The goal is to evaluate each product code and generate a PDF for those that end with a digit. A regular expression (regex) is defined to match strings that end with a digit. The pattern \d$ is explained as follows:

  • \d matches any digit (0-9).
  • $ asserts that the digit must be at the end of the string.

A foreach loop iterates through each product code in the productCodes list. For each code, the IsMatch() method checks whether the product code ends with a digit (based on the regex pattern). If the condition is true, the code inside the if block is executed.

Using ChromePdfRenderer's RenderHtmlAsPdf() method, PDF reports are generated for the codes that end with a digit. These new PDFs are stored in the PdfDocument object created, and each one is saved using Pdf.SaveAs(). We have used the code names to create unique names for each document, avoiding overwriting each other.

Formatting Strings for PDF Reports

Before including string data in your PDF, you may want to format it. For example, you can trim whitespace, convert characters to uppercase, or capitalize them:

string str = " example ";
string formatted = str.Trim().ToUpper(); // Result: "EXAMPLE"

Why Use IronPDF for Generating PDFs in .NET?

Key Benefits of IronPDF for String-Based PDF Generation

IronPDF is a powerful .NET PDF library that simplifies working with PDFs. Thanks to its easy installation and variety of integration options, you'll be able to create and edit PDF documents to fit your needs in no time.

IronPDF simplifies the process of creating PDFs from string and HTML content in several ways:

Want to see more of IronPDF in action? Be sure to check out the extensive how-to guides and code examples for this robust library.

Seamless Integration with .NET and C# Libraries

IronPDF integrates seamlessly with .NET and C#, allowing you to leverage its powerful PDF generation features alongside your existing projects. It supports asynchronous operations, making it ideal for large-scale or performance-critical applications.

Conclusion

String manipulation is a fundamental skill that plays a crucial role in many C# applications, from basic data processing to advanced tasks like generating dynamic PDFs. In this article, we explored several methods for extracting the last character from any local or public string, a task that frequently arises in scenarios such as categorizing data, validating inputs, or preparing content for reports. We also explored how to use this to create dynamic PDF documents with IronPDF. Whether you used Substring(), array indexing, or the modern ^1 operator introduced in C# 8.0, you can now manipulate strings in C# proficiently.

IronPDF stands out for its ease of use and versatility, making it a go-to tool for developers working with PDFs in .NET environments. From handling large volumes of data to supporting asynchronous operations, IronPDF can scale with your project needs, providing a rich set of features to handle text extraction, watermarks, custom headers and footers, and more.

Now that you've seen how string manipulation and PDF generation can be used together, it's time to try it yourself! Download the free trial of IronPDF and begin transforming your string data into beautifully formatted PDFs. Whether you're creating reports, invoices, or catalogs, IronPDF gives you the flexibility and power you need to elevate your document generation process.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

bullet_checkedNo credit card or account creation required
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge related to IronPDF Product Demo

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required