Hi,

I'm trying to insert a number between a string.

For e.g. : If I have a string like "C23H24N1O" or "CHAl"

Then it should be "C23H24N1O1" or "C1H1Al1"


If a capital letter doesn't carry any numerical then it should insert "1" next to it

If a capital letter carry a small letter (for e.g. "Na") and if this small letter doesn't carry any number then it should insert "1" (for e.g. "Na1")

If these carry numbers then no alterations should be made.

private void button17_Click(object sender, EventArgs e)
        {
            textBox5.Clear();
            for (int i = 0; i < textBox4.Text.Length; i++)
            {
                if ((textBox4.Text[i] >= 'A') && (textBox4.Text[i] <= 'Z'))
                {
                    textBox5.AppendText(textBox4.Text[i].ToString());
                    if ((textBox4.Text[i + 1] >= 'A') && (textBox4.Text[i + 1] <= 'Z') || (textBox4.Text[i + 1] >= ' '))
                    {
                        try
                        {
                            if ((textBox4.Text[i + 1] >= 'a') && (textBox4.Text[i + 1] <= 'z'))
                            {
                                if ((Convert.ToInt32(textBox4.Text[i + 2]) >= 1) && ((Convert.ToInt32(textBox4.Text[i + 2]) <= 9)))
                                {
                                    textBox5.AppendText(textBox4.Text[i + 1].ToString() + textBox4.Text[i + 2].ToString());
                                }
                                else
                                {
                                    textBox5.AppendText(textBox4.Text[i + 1].ToString() + "1");
                                }
                            }
                            else if ((textBox4.Text[i + 1] >= 'A') && (textBox4.Text[i + 1] <= 'Z'))
                            {
                                if ((textBox4.Text[i + 2] >= 'a') && (textBox4.Text[i + 2] <= 'z'))
                                {
                                    textBox5.AppendText(textBox4.Text[i + 2] + "1");
                                }
                                else
                                {
                                    textBox5.AppendText("1");
                                }
                            }
                        }
                        catch { }
                    }
                    else
                    {
                        textBox5.AppendText(textBox4.Text[i+1].ToString());
                    }
                }
                else 
                {
                    textBox5.AppendText(textBox4.Text[i].ToString());
                }
               
            }
        }

This this what I have tried but still there is some functionality missing.

Please help me..


regards,
Srik

Dani AI

Generated

A compact, robust approach is to treat each element symbol as "one uppercase letter plus at most one lowercase letter" and only append 1 when that symbol is not immediately followed by a digit. This builds on 's regex idea and keeps the logic tighter than scanning characters with explicit i+1 indexing (which is where the original loop can throw out‑of‑range errors). 's suggestion to use Char helpers is valid if you prefer a manual parser; below is an idiomatic, safe C# regex solution.

using System.Text.RegularExpressions;

string NormalizeFormula(string formula)
{
    // match one uppercase + optional lowercase, only when NOT followed by a digit
    return Regex.Replace(formula, @"([A-Z][a-z]?)(?!\d)", m => m.Groups[1].Value + "1");
}

Notes and edge cases:

  • Multi‑digit counts (C12, H22 etc.) are preserved because the negative lookahead prevents matching when a digit follows.
  • Avoid using replacement "$11" — that can be ambiguous; the MatchEvaluator lambda above appends the literal "1" safely.
  • If your input can include charges or signs (Na+, Cl-) and you do not want to add "1" before a sign, change the lookahead to exclude them, e.g. @"([A-Z][a-z]?)(?!\d|[+-])".
  • If you must support three‑letter temporary symbols or nonstandard tokens, expand the pattern to [A-Z][a-z]{0,2} or write a small tokenizer using Char.IsUpper/IsLower/IsDigit (the latter gives finer control for parentheses, dots, hydration, and nested groups).
  • For very large inputs, add RegexOptions.Compiled for speed.

This keeps the transformation minimal, readable, and safe while addressing the specific failures seen in the posted loop code.

Recommended Answers

All 6 Replies

Perhaps you could make use of the fact that in the periodic table only 13 elements have 1 letter al the rest have two or three(rare).
Could you elaborate on the fact you use two textboxes?

Perhaps you could make use of the fact that in the periodic table only 13 elements have 1 letter al the rest have two or three(rare).
Could you elaborate on the fact you use two textboxes?

Hi,

Thanks for the reply.

One is the text box (textbox4) which contains the formula and the other is just to display the result (textbox5)

using System;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            Regex reg = new Regex("[A-Z][a-z]*[0-9]*");
            String str = "C23H24Na1O";

            StringBuilder sb = new StringBuilder();
            foreach (Match m in reg.Matches(str)) {
                sb.Append(m.Value);
                if (Char.IsDigit(m.Value[m.Value.Length - 1]) == false) {
                    sb.Append(1);
                }
            }

            Console.WriteLine(sb.ToString());
            Console.ReadLine();
        }
    }
}

This shows how to use a Regular expression to break your string into parts then check each part for the number condition. Line 8 says "I need 1 capital letter, followed by optional (the *) lower case letters followed by optional numbers". Line 14 checks if the last character in each section is a number, and if not add "1" to our string.

commented: Regex is a nice thing to master! +8
commented: great +0

Hi Momerath,

Thanks a lot.

Please mark this thread solved if it is :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.