- Home /
Replace String Characters with certain Numbers
How can I replace every "a" to 1, and every "b" to 2 ... in a String? I want to save the outcome as one integer in the end.
Thanks
Answer by Berenger · Mar 19, 2014 at 08:22 AM
"banana".Replace('a', '1').Replace('b', '2');
=> "21n1n1"
Answer by Johannski · Mar 19, 2014 at 08:34 AM
You can cast chars to ints, then you get their ascii value. I made a small example, of how you could convert your numbers:
using UnityEngine;
using System.Collections;
public class StringToNumbers : MonoBehaviour {
string hello = "ABC abc Hello World!";
string helloNumbers = "";
// Use this for initialization
void Start () {
hello = hello.ToLower();
foreach (char c in hello.ToCharArray())
{
//96 because a has an asciivalue of 97
helloNumbers +=((int)c - 96).ToString() + " ";
}
Debug.Log(helloNumbers);
}
// Update is called once per frame
void Update () {
}
}
The Output would be: 1 2 3 -64 1 2 3 -64 8 5 12 12 15 -64 23 15 18 12 4 -63 But I'm not quite sure, for what you need it.
The other answer did the trick, but I will keep this in $$anonymous$$d. Thanks :)
Your answer
Follow this Question
Related Questions
Spawn Script problem 2 Answers
Is there something like Animator.StringToHash() but for tags? 0 Answers
Using Strings To Call Function 1 Answer
Why can't I save an array? 1 Answer
Sequential GameObject Activation 2 Answers