.NET HELP

C# String Methods (How it Works for Developers)

Chipego
Chipego Kalinda
April 3, 2025
Share:

Working with PDFs in C# involves not just rendering and formatting content, but also manipulating text to meet your needs. Whether you’re extracting, searching, or editing text within a PDF, knowing how to leverage C# string methods can significantly enhance your workflow. In this article, we'll explore common C# string operations, how they apply to IronPDF, and how you can use them to streamline your PDF processing tasks.

An Introduction to Using String Methods with IronPDF

C# provides a variety of string methods that allow you to handle text in versatile ways. From basic operations like concatenation and replacement to advanced techniques like regular expressions, these methods are essential when manipulating content within PDFs.

IronPDF, a powerful library for working with PDFs in C#, integrates seamlessly with these string functions, giving developers a flexible toolset for handling PDF content. Whether you need to extract text, search for patterns, or manipulate content, understanding how to use C# string methods with IronPDF will help you achieve your goals.

IronPDF: A Powerful C# PDF Library

C# String Methods (How it Works for Developers): Figure 1 Add from PixabayUpload

or drag and drop an image here

Add image alt text

IronPDF is a robust PDF library for .NET, designed to simplify PDF creation, manipulation, and automation. Whether you need to generate dynamic documents or extract and edit content, IronPDF offers a seamless solution with a rich set of features.

Key Features

  • HTML to PDF Conversion: Easily convert HTML content into fully styled PDFs.
  • Text Extraction: Extract and manipulate text from existing PDFs.
  • PDF Editing: Add text, images, and annotations to PDFs or update existing content.
  • Digital Signatures: Add secure digital signatures to PDFs.
  • PDF/A Compliance: Ensure your PDFs meet strict archiving standards.
  • Cross-Platform Support: Works on .NET Framework, .NET Core, and .NET 5/6 across Windows, Linux, and macOS.

IronPDF provides a comprehensive suite of tools to handle all your PDF needs with ease and efficiency. Start exploring its powerful features today with a free trial and see how IronPDF can streamline your PDF workflows!

Basic String Operations in C#

Concatenation

Concatenation is one of the simplest operations when working with strings. In C#, there are multiple ways to join two or more strings together, with the most common methods being the + operator and String.Concat().

string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2;  // Output: "Hello World"
string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2;  // Output: "Hello World"

C# String Methods (How it Works for Developers): Figure 2 Add from PixabayUpload

or drag and drop an image here

Add image alt text

When working with IronPDF, you might need to concatenate strings to create a full document or manipulate text in extracted content. For example, you can merge the header and body of a PDF document as strings before applying formatting:

var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;

This demonstrates how simple string concatenation can merge specified substrings into one cohesive block. As we’ll see later, such concatenated strings can be used to build dynamic content for PDFs.

PDF Output:

C# String Methods (How it Works for Developers): Figure 3 Add from PixabayUpload

or drag and drop an image here

Add image alt text

PDF Output String

When creating a new document using IronPDF, the specified index position of text strings will be critical for determining where elements like the header or body appear on the page. In this way, the current string object can directly impact layout decisions.

Text Formatting in PDFs

Once you’ve extracted and manipulated the text, you might need to format it before adding it to a new PDF. IronPDF allows you to set font styles, sizes, and even positioning using the RenderHtmlAsPdf conversion feature, where C# string methods can help you generate formatted content dynamically.

For example, you could create dynamic headers and body content by concatenating strings with HTML tags:

string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";

This HTML content can then be converted into a well-formatted PDF using IronPDF:

PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");

PDF Output:

C# String Methods (How it Works for Developers): Figure 4 Add from PixabayUpload

or drag and drop an image here

Add image alt text

This approach allows you to easily generate PDFs with dynamically generated content while ensuring the right text formatting. By generating a new string from dynamic content, you can pass formatted string arrays of HTML content to IronPDF, ensuring that the PDF output matches your requirements.

Searching for a Specified Substring

In many cases, you’ll need to check if a string contains a specified substring. The Contains() method is useful for this, as it returns true or false based on whether the specified string exists within the target string.

string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");

Finding the Specified Position of a Character

To find a specified character within a string, the IndexOf() method is particularly useful. It returns the specified position where the character or substring first appears in the string.

string str = "Invoice Number: 12345"; int position = str.IndexOf('5'); // Returns the position of the first '5'
string str = "Invoice Number: 12345"; int position = str.IndexOf('5'); // Returns the position of the first '5'

This can be handy when extracting dynamic data such as numbers or dates from text within a PDF using IronPDF.

Advanced String Techniques for PDF Automation

Regular Expressions

For more complex text extraction, regular expressions (Regex) offer a powerful tool for pattern matching. With Regex, you can extract structured data, such as dates, invoice numbers, or even email addresses, from unstructured text within a PDF.

using System.Text.RegularExpressions;
string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
    string date = match.Value;  // Output: "02/11/2025"
}
using System.Text.RegularExpressions;
string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
    string date = match.Value;  // Output: "02/11/2025"
}

Regular expressions can be particularly useful for documents with variable content or specific formats you need to capture. Using IronPDF to extract raw text combined with regular expressions helps automate tasks like form processing, data validation, and reporting.

StringBuilder for Large Text

When working with large blocks of text, such as multiple pages of content or data-driven reports, it’s more efficient to use a StringBuilder instead of regular string concatenation. StringBuilder is optimized for scenarios where you need to append or modify large amounts of text without creating multiple intermediate string instances.

StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();

IronPDF can handle large PDF documents, and integrating StringBuilder in your workflow ensures better performance when generating or manipulating large texts within PDFs.

Checking if a String Instance Matches a Pattern

The Equals() method checks whether two string instances match, meaning they have the same value. This is particularly useful for validation or comparisons within PDF content.

string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value
string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value

In IronPDF, this could be applied when comparing extracted text to ensure it matches a desired format or value.

Handling Unicode Characters

When working with text in PDFs, you may need to manipulate or check for specified Unicode characters. The IndexOf() method can also be used to find the position of a specific unicode character within a string.

string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character
string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character

PDF Output

C# String Methods (How it Works for Developers): Figure 5 Add from PixabayUpload

or drag and drop an image here

Add image alt text

Additionally, converting strings to a unicode character array can be useful when working with text in different languages or symbols:

char[] unicodeArray = "Hello * World".ToCharArray();
char[] unicodeArray = "Hello * World".ToCharArray();

This allows for more precise manipulation of characters, especially when dealing with PDFs in various languages or formats.

Substring Extraction and Manipulation

Another powerful feature when working with strings is the ability to extract a specified substring. The Substring() method lets you select portions of a string starting from a specified index position. This is essential for extracting meaningful data from PDF content.

string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"
string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"

This technique is useful when processing invoices or any form of structured text within a PDF.

Generating PDFs with C# String Methods

Let’s put everything together and look at a more comprehensive example of how C# string methods can be used to generate a PDF using IronPDF. This example will demonstrate how to extract text, manipulate it with string methods, and then generate a formatted PDF.

Example: Creating a Custom Invoice PDF

Imagine we need to generate an invoice PDF dynamically, pulling information like the customer’s name, address, and items purchased. We'll use various string methods to format and manipulate the data before generating the final PDF.

using IronPdf;
using System;
using System.Text;
class Program
{
    static void Main()
    {
        // Sample customer data
        string customerName = "John Doe";
        string customerAddress = "123 Main Street, Springfield, IL 62701";
        string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };
        // Start building the HTML content for the invoice
        StringBuilder invoiceContent = new StringBuilder();
        // Adding the header
        invoiceContent.AppendLine("<h1>Invoice</h1>");
        invoiceContent.AppendLine("<h2>Customer Details</h2>");
        invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
        invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");
        // Adding the list of purchased items
        invoiceContent.AppendLine("<h3>Items Purchased</h3>");
        invoiceContent.AppendLine("<ul>");
        foreach (var item in purchasedItems)
        {
            invoiceContent.AppendLine("<li>" + item + "</li>");
        }
        invoiceContent.AppendLine("</ul>");
        // Calculate total cost (basic manipulation with string methods)
        double totalCost = 0;
        foreach (var item in purchasedItems)
        {
            string priceString = item.Substring(item.LastIndexOf('$') + 1);
            double price = Convert.ToDouble(priceString);
            totalCost += price;
        }
        // Adding total cost
        invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");
        // Convert the HTML to PDF using IronPDF
        var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());
        // Save the generated PDF
        pdf.SaveAs("Invoice_Johndoe.pdf");
        Console.WriteLine("Invoice PDF generated successfully.");
    }
}
using IronPdf;
using System;
using System.Text;
class Program
{
    static void Main()
    {
        // Sample customer data
        string customerName = "John Doe";
        string customerAddress = "123 Main Street, Springfield, IL 62701";
        string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };
        // Start building the HTML content for the invoice
        StringBuilder invoiceContent = new StringBuilder();
        // Adding the header
        invoiceContent.AppendLine("<h1>Invoice</h1>");
        invoiceContent.AppendLine("<h2>Customer Details</h2>");
        invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
        invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");
        // Adding the list of purchased items
        invoiceContent.AppendLine("<h3>Items Purchased</h3>");
        invoiceContent.AppendLine("<ul>");
        foreach (var item in purchasedItems)
        {
            invoiceContent.AppendLine("<li>" + item + "</li>");
        }
        invoiceContent.AppendLine("</ul>");
        // Calculate total cost (basic manipulation with string methods)
        double totalCost = 0;
        foreach (var item in purchasedItems)
        {
            string priceString = item.Substring(item.LastIndexOf('$') + 1);
            double price = Convert.ToDouble(priceString);
            totalCost += price;
        }
        // Adding total cost
        invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");
        // Convert the HTML to PDF using IronPDF
        var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());
        // Save the generated PDF
        pdf.SaveAs("Invoice_Johndoe.pdf");
        Console.WriteLine("Invoice PDF generated successfully.");
    }
}

Explanation

  • Data Setup: We start with sample customer data, including the customer’s name, address, and a list of items purchased.
  • StringBuilder: We use a StringBuilder to build the HTML content for the invoice. This allows us to efficiently append each part of the content (header, customer details, purchased items list, and total cost) without creating multiple intermediate string instances.

    • String Manipulation:

      • For each item, we extract the price (after the $ symbol) and calculate the total cost. This is done using Substring() to get the specified substring, and Convert.ToDouble() to convert it to a numeric value.
    • The total cost is then formatted to two decimal places for a clean and professional display.
  • HTML to PDF Conversion: After creating the invoice content in HTML format, we use IronPDF’s RenderHtmlAsPdf() method to generate a PDF. The result is saved as Invoice_Johndoe.pdf.

By using IronPDF's powerful HTML-to-PDF conversion and combining it with C# string manipulation techniques, you can automate the creation of dynamic documents, whether they’re invoices, reports, or contracts.

PDF Output

C# String Methods (How it Works for Developers): Figure 6 Add from PixabayUpload

or drag and drop an image here

Add image alt text

Conclusion

Mastering C# string methods when working with IronPDF can streamline your PDF processing tasks, whether you’re extracting, editing, or formatting content. By leveraging techniques like string concatenation, substring extraction, and regular expressions, you gain full control over the text in your PDFs, enabling more dynamic and efficient workflows.

IronPDF provides powerful PDF manipulation capabilities that work seamlessly with C# string methods. Whether you’re handling text extraction, searching for patterns, or automating content generation, combining IronPDF with C# string operations will save you time and effort.

Want to see how IronPDF can help with your PDF automation? Try out the free trial today and explore its full potential!

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
C# Interlocked (How it Works for Developers)
NEXT >
HTML Prettifier (How it Works for Developers)