Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
2.75/5 (4 votes)
See more:
hello guys.
i have a question, how can we find out position of a character in a string value.
like i type arun in a textbox, then i type 'u' in next textbox.
then on the click of buttn it displays the position of 'u' in 'arun'.
thanx for ur valuable suggestion ,but there is still a problum,
wt will we do if a character is repetation itself and we need to find out find out it position everytime.like position of 'a 'in 'ajay' is at index 0 and 2 .wt should i do to find both positions
Posted
Updated 29-Nov-10 21:24pm
v3

On the click event of the button, Write this:

C#
String myName=TextBox1.Text;
String findCharacter=TextBox2.Text;

Int myCharacterIsAt=myName.IndexOf(findCharacter,1);
//It will return the index staring from zero.
// ie. in case of "u" you will get 2 as index

//Display the result
TextBox3.Text=myCharacterIsAt + 1; // Will return 3 in your example
 
Share this answer
 
Since the question changed, so will the answer!

Well i would be using a for loop.

C#
int i=0;
String myName=TextBox1.Text;
String findCharacter=TextBox2.Text;

for(i=0;i<myname.length;i++)>
{
 if(myName[i]==findCharacter)
 {
  TextBox3.Text=(i+1) + " ";
 }
}
 
Share this answer
 
v2
So, what is the issue?

On click of button, get the text present in textbox2 and use it to search in text of textbox1. You can use one of various properties based on your need. Like IndexOf, etc. Have a look at the properties of string here.[^]
 
Share this answer
 
Try this out: :-D

C#
public partial class Form1 : Form
{
  // declaration of variables
  string text = "";
  char character;
  int charPos = 0;
  string strCharPos;

  public Form1()
  {
    InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
    // data
    text = textBox1.Text;
    // search criteria
    character = Convert.ToChar(textBox2.Text);

    // find character
    for (int idx = 0; idx < text.Length; idx++)
    {
      if (text[idx] == character)
      {
        charPos = idx + 1;
        strCharPos = strCharPos + Convert.ToString(charPos) + ", ";
        label1.Text = strCharPos;
      }
    }

    // Reset data
    strCharPos = "";
    charPos = 0;
    text = "";
    character = '\0';
  }
}
 
Share this answer
 
Hi,

Try the following Code...

string sText = "AJAY";
string sIndex=string.Empty;

for(int a=0;a<sText.Length;a++)
{
  if(sText[a].ToString().Equal("A"))
  {
    if(sIndex != string.Empty)
    {
      sIndex += ",";
    }   
    sIndex += (a+1);
  }
}

// Get sIndex value is your output.

Cheers :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900