Michael Arsenyan
Michael Arsenyan

Reputation: 3

C# subscript string including variable

I know that in C# to write subscript, I should use Unicode for example I want to write H2O , I should write

String str = "H"+"\x2082"+ "O"

But I want to put variable type of int instead of 2 in formula How can I create a string with variable, which is written in subscript?

Upvotes: 0

Views: 1769

Answers (4)

Mike
Mike

Reputation: 1091

Maybe we don't understand your question. Several of the answers above seem correct. Does this work?

static string GetSubscript(int value)
{
  StringBuilder returnValue = new StringBuilder();
  foreach (char digit in value.ToString())
    returnValue.Append((char)(digit - '0' + '₀'));
  return returnValue.ToString();
}

string waterFormula = "H" + GetSubscript(2) + "0"  // H₂O
string methaneFormula = "CH" + GetSubscript(4) // CH₄

Upvotes: 0

Douglas
Douglas

Reputation: 54897

In Unicode, the subscript digits are assigned consecutive codepoints, ranging from U+2080 to U+2089. Thus, if you take the Unicode character for subscript 0 – namely, '₀' – then you can obtain the subscript character for any other digit by adding its numeric value to the former's codepoint.

If your integer will only consist of a single digit:

int num = 3;
char subscript = (char)('₀' + num);   // '₃'

If your integer may consist of any number of digits, then you can apply the same addition to each of its digits individually. The easiest way of enumerating an integer's digits is by converting it to a string, and using the LINQ Select operator to get the individual characters. Then, you subtract '0' from each character to get the digit's numeric value, and add it to '₀' as described above. The code below assumes that num is non-negative.

int num = 351;
var chars = num.ToString().Select(c => (char)('₀' + c - '0'));
string subscript = new string(chars.ToArray());   // "₃₅₁"

Upvotes: 1

dav_i
dav_i

Reputation: 28137

This wikipedia article shows you all the unicode codes for super and subscript symbols.

You can simply create a method which maps these:

public string GetSubScriptNumber(int i)
{
    // get the code as needed
}

I will give a few hints to help you along:

  • Unfortunately you can't just do return "\x208" + i so you'll need to do a switch for the numbers 0-9 or add the integer to "\x2080".
  • If you only need 0-9 then do some error checking that the input is in that range and throw an ArgumentOutOfRangeException
  • If you need all ints then you may find it easier splitting it up into each digit and getting a char for each of those - watch out for negative numbers but there is a character for subscript minus sign too!

To include the number in your string, you can use something like String.Format:

String.Format("H{0}O", GetSubScriptNumber(i))

Upvotes: 1

Nisus
Nisus

Reputation: 824

Try to escape it

String str = "H" + "\\x2082" + "O";

or use verbose strings

String str = "H" + @"\x2082" + "O";

Upvotes: 0

Related Questions