breaking a string inside an array to a character in C#

sorry for the weird title, I am having a hard time explaining it. What I want is to compare the characters in my string like this:

stringa = new string[3];

for (int x = 0; x < stringa.GetLength(0); x++)
{
    Console.WriteLine("String" + (x + 1) + ":");
    stringa[x] = Console.ReadLine();
}

for(int x = 0;x < stringa.GetLength(0);x++)
{
    Console.WriteLine(stringa[x]);
}

What I want is that now that I have stringa[x], I want to compare every character inside that string. Is there any way I can do that without using any temporary variables?

Answers


You can get a character within a string by indexing. For instance:

string myString = "Test string";
Console.WriteLine(myString[0]);

Will write the character 'T'

In your case, you could put another for loop inside your second one and call stringa[x][y] to get the y'th character in stringa[x], but it's more efficient to store stringa[x] in a local variable and index that, like so:

for(int x = 0;x < stringa.Length(0);x++)
{
    // Store stringa[x] so that we don't have to keep indexing stringa
    string stringx = stringa[x];
    for(int y = 0;y < stringx.Length(0);x++)
    {
        // Do some comparison on stringx[y]
    }
}

Each character of a string can be accessed by index, so where the following shows the 1st string:

Console.WriteLine(stringa[0]);

This code shows the 1st char from the 1st string:

Console.WriteLine(stringa[0][0]); 

To determine the length of each individual string, for looping purposes, you can find the length of the specific string like:

stringa[x].Length

Need Your Help

Extremely slow SELECT statement with WHERE on a FK field

sql sql-server tsql sql-server-2014-express

I have this query below, and it's extremely slow. It takes almost 2 minutes for run to return 3,008 records out of a table with 99 million records. The first query where it gets "Article" data is...

Google CSE query terms with wildcards

google-custom-search

I've tried to look in the official documentation but to no avail.