Home > Software engineering >  How to check characters after a specific part of a string in C#?
How to check characters after a specific part of a string in C#?

Time:12-16

I am trying to find a specific value inside a string, and then check the characters which come after the value.

I got the first part and can find the values I need but want to check after every value I find if any of the ten characters in front of it in the string are numbers or not.

here is the first part I got so far:

     public class Text_Value : MonoBehaviour
 {  
     [SerializeField]
     private TMP_Text Text;
 
     public List<string> Values = new List<string>();
 
     private int ChestCircumference;
 
     private int BodyHeight;
 
     private int HighHipCircumference;
 
     private int BellyCircumference;
 
     private int CharacterIndex = 0;
 
 
     // Start is called before the first frame update
     void Start()
     {
         StartCoroutine(GetValues());
     }
 
     // Update is called once per frame
     void Update()
     {
         
     }
 
 
     IEnumerator GetValues()
     {
         if (Text.text == "No Data")
         {
             yield return new WaitForSeconds(0.1f);
 
             Debug.Log("Text Value Finder: Wating For Text Data");
 
             StartCoroutine(GetValues());
         }
         else if (Text.text != "No Data")
         {
             foreach (string value in Values)
             {
                 if (Text.text.Contains(value))
                 {
                     Debug.Log("Value Found: "   value);
                 }
                 else if (!Text.text.Contains(value))
                 {
                     Debug.Log("Missing Value: "   value);
                 }
             }
         }
     }
 
 }

I think I need to use a loop inside the foreach loop, one that will go over the next ten characters, but not sure how to do it.

An example of the string would be:

"Collar Circumference":39.102776,"Neck Base Circumference":42.982479"

CodePudding user response:

As said you could use Regex.Matches like e.g.

var matches = Regex.Matches(Text.text, "\"(.*?)\":(.*?)(?=,|$)");
foreach(var match in matches)
{
    var key = match.Groups[1];
    var valueString = match.Groups[2];
    if(float.TryParse(valueString, out var value))
    {
        Debug.Log($"Found match for {key} with value = {value}");
    }
}

See Regex Example and explanation


However, if this is actually a JSON then you should rather use a proper c# representation and actually parse the JSON e.g. depending on the complexity of your JSON simply using the built-in JsonUtility

Assuming you have access to the JSON generation and can rather use names without spaces like

{
    "ChestCircumference":12.34,
    "BodyHeight":1.23,
    "HighHipCircumference":0.23,
    "BellyCircumference":0.34567,
    "CharacterIndex": 3
}

In your case you could e.g. wrap your values like

// The class name doesn't matter in JSON
[Serializable]
public class Config
{
     public float ChestCircumference;
     public float BodyHeight;
     public float HighHipCircumference;
     public float BellyCircumference;
     public int CharacterIndex = 0;
}

and then simply do

var config = JsonUtility.FromJson<Config>(jsonString);

Or if changing the JSON is not an option use Newtonsoft JSON like e.g.

{
    "Chest Circumference":12.34,
    "Body Height":1.23,
    "High Hip Circumference":0.23,
    "Belly Circumference":0.34567,
    "Character Index": 3
}

Then

[Serializable]
public class Config
{
     [JsonProperty ("Chest Circumference")]
     public float ChestCircumference;
     [JsonProperty ("Body Height")]
     public float BodyHeight;
     [JsonProperty ("High Hip Circumference")]
     public float HighHipCircumference;
     [JsonProperty ("Belly Circumference")]
     public float BellyCircumference;
     [JsonProperty ("Character Index")]
     public int CharacterIndex = 0;
}

And then do

var config = JsonConvert.DeserializeObject<Config>(jsonString);

CodePudding user response:

The easiest way to access specific values, is to parse the string and put it in a dictionary, where the name of the part is used as key:

string input =
    "\"Collar Circumference\":39.102776,\"Neck Base Circumference\":42.982479";

var dict = input.Split(",\"")
    .Select(p => p.TrimStart('"').Split("\":"))
    .ToDictionary(x => x[0], x => Double.Parse(x[1]));

This test ...

double collar = dict["Collar Circumference"];
double neckBase = dict["Neck Base Circumference"];
Console.WriteLine(collar);
Console.WriteLine(neckBase);
foreach (var entry in dict) {
    Console.WriteLine($"\"{entry.Key}\" = {entry.Value}");
}

... prints:

39.102776
42.982479
"Collar Circumference" = 39.102776
"Neck Base Circumference" = 42.982479

This assumes that all values can be expressed as double. If this is not the case, just keep them as string:

...
.ToDictionary(x => x[0], x => x[1]);
  • Related