Reputation: 3
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
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
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
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:
return "\x208" + i
so you'll need to do a switch for the numbers 0-9
or add the integer to "\x2080"
.0-9
then do some error checking that the input is in that range and throw an ArgumentOutOfRangeException
int
s 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
Reputation: 824
Try to escape it
String str = "H" + "\\x2082" + "O";
or use verbose strings
String str = "H" + @"\x2082" + "O";
Upvotes: 0