Facebook

CharAt in C#: A Practical Guide

by Michael Sacco Published August 31, 2023
The cover for CharAt in C#: A Practical Guide

Introduction

If you use Unity to make a word-based game like, idk, Wordle, having a method like Javascript’s CharAt in C# is helpful.

CharAt returns the character at a specific index in a string. For example, the string “Hola mami” is made up of 9 characters, "H", "o", "l", "a", " ", "m", "a", "m", and "i". In Javascript, you can use CharAt to get the character at a specific position. In this quick article, I will explain everything you need to know about using CharAt in C#.

Quick help

  • Use the index accessor [ ] to get the character at a specific index in a string.
  • To get the first character in a string, use myString[0].
  • To get the last character in a string, use myString[myString.Length - 1].

How does CharAt work in Javascript?

For example, if we want to get the character 'o’, from the string "Hola mami", we would use charAt with an index of 1.

let text = "Hola mami";
let letter = text.charAt(1);

The CharAt equal in C# is similar and even more straightforward. Instead of an extension method (CharAt), use the index accessor.

How do I use CharAt in C#?

In this example, I will show you how to get a character from a string in a complete component. As I mentioned, you use the index accessor. In other words, you treat the string like an array and use the array index.


using UnityEngine;

public class CharAtExample : MonoBehaviour

{
  public string hola = "Hola mami";
  void Start()
  {
    char o = hola[1];
    Debug.Log(o);
  }
}

The array indexer is like an implicit method that returns the value of that item in the array. If you still need clarification, don’t worry! I wrote an interactive demo script to help you apply this concept.

Interactive demo script

I wrote a small script to help you play around with this concept. Create a new component using this script. Then, add the script to an object in your scene. This component will write the result of the C# version of CharAt to the console. I wrap the index for you so you never encounter out-of-bounds exceptions.

using UnityEngine;

[ExecuteAlways]
public class InteractiveCharAt : MonoBehaviour
{
  public string testString = "Hi, mom!";
  public int indexToFetch = 0;

  private void Update()
  {
    if (indexToFetch >= testString.Length)
      indexToFetch = 0;
    
    if (indexToFetch < 0)
      indexToFetch = testString.Length - 1;
    
    Debug.Log(testString[indexToFetch]);
  }
}

In the inspector, try changing the test string to different values.

What happens if you set the string to "Michael is the goat of all time"? (That’s me, btw).

What happens when you change the index around?

Does the index need to be less than the string length?

Yes. Put an index greater than or equal to the string length. You will get an error. “IndexOutOfRangeException: Index was outside the bounds of the array.” This error indicates that the index is greater than the array’s length.

To resolve this error, ensure that your index is less than or equal to the array’s length. In this case, we are treating the string like an array. So, the index needs to be less than the length of the string.

How do I get the string length?

To get the length of the string, use the .Length property. Too easy.

string myString =I like tea”;
Debug.Log(myString.Length);

Why does the index accessor return a char?

A single character within a string is a char type. One error to watch out for when using char constructors is the Too Many Characters error.

Is the index accessor 0-based?

Yes. The index accessor is a zero-based index, meaning that the first character in a string is at index 0.

Is there another way to get the che character at a specific index?

Yes. One other option is the Substring() method. I recommend against using the Substring() method for this scenario. The Substring() method is less scannable than the index accessor.

The index accessor is the simplest and most efficient way.

How do I use the Substring method to get a specific character?

Substring expects a start index and a length. That’s why it’s less scannable. In our case, the start index would be the index accessor. The length would be 1.

string text = "Big dawg";
string letter = text.Substring(1,1);

// Logs ‘i' to console.
Debug.Log(letter);

Try it yourself

A good lesson is only complete with a trial. You must practice to understand new concepts. So, it’s time to apply yourself. Write a new CharAt method in Unity. The method should take a string and an index. Then, it should return the character for that index. In other words, write a wrapper for the index accessor method.

If you get stuck, re-read the article to see if you still need to catch up on a critical concept.

Conclusion

In conclusion, the index accessor is the C# version of JavaScript’s CharAt method. To access the character at a specific index in a string, use the [ ] operator. For example, you would use myString[0] to get the first character in a string. To get the last character in a string, you would use myString[myString.Length - 1].

It is important to note that the index must be less than or equal to the length of the string. If you try to access a character at an index greater than or equal to the size of the string, you will get an error.

You can use the index’s absolute value (That’s Mathf.Abs()) to ensure that it is always positive. For example, this math operation can be helpful if you use the index to iterate over a string. But I recommend looping the index like I did in the interactive demo. You can also use Modulo for this.

Use the OnValidate() method to ensure the index is valid before accessing a character. Using OnValidate() to check your data can help prevent errors.

Being comfortable using the index accessor with strings in Unity is crucial. I hope this guide helped!

Free download: Indie Game Marketing Checklist

Download now

Category

programming

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free