开发者

Convert a word into character array

How do I convert a word into a character array?

Lets say i have the word "Pneumonoultramicroscopicsilicovolcanoconiosis" yes this is a word ! I would like to take this word and assign a numerical value to it.

 a = 1
 b = 2
 ... z = 26

 int alpha = 1;
 int Bravo = 2;

basic code

if (testvalue == "a")
{
    Debug.WriteLine("TRUE A was found in the string"); // true
    FinalNumber = Alpha + FinalNumber;
    Debug.WriteLine(FinalNumber);
}

if (testvalue == "b")
{
    Debug.WriteLine("TRUE B was found in the string"); // true
    FinalNumber = Bravo + FinalNumber;
    Debug.WriteLine(FinalNumber);
}

My question is how do i get the the word "Pneumonoultramicroscopicsilicovolcanoconiosis" into a char string so that I开发者_高级运维 can loop the letters one by one ?

thanks in advance


what about

char[] myArray = myString.ToCharArray();

But you don't actually need to do this if you want to iterate the string. You can simply do

for( int i = 0; i < myString.Length; i++ ){
  if( myString[i] ... ){
    //do what you want here
  }
}

This works since the string class implements it's own indexer.


string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = word.ToCharArray();

Voilá!


you can use simple for loop.

string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
int wordCount = word.Length;
for(int wordIndex=0;wordIndex<wordCount; wordIndex++)
{
    char c = word[wordIndex];
   // your code
}


You can use the Linq Aggregate function to do this:

"wordsto".ToLower().Aggregate(0, (running, c) => running + c - 97);

(This particular example assumes you want to treat upper- and lower-case identically.)

The subtraction of 97 translates the ASCII value of the letters such that 'a' is zero. (Obviously subtract 96 if you want 'a' to be 1.)


you can use ToCharArray() method of string class

string strWord = "Pneumonoultramicroscopicsilicovolcanoconiosis"; 
char[] characters = strWord.ToCharArray(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜