Parth Desai
Parth Desai

Reputation: 209

Keep Spaces After replacing

I am having string[] [value1 value2 value3] and I want to replace it by 10 20 30 and show it in message box. But after replacing it removes white spaces and displays as 102030

string[] values = headerData.Split(new string[] { "<#Tag(", ")>" }, // value1 value2 value3 StringSplitOptions.RemoveEmptyEntries);
string text = "";
string val1 = "";

foreach (string val in values) 
{
   foreach(GlobalDataItem gdi in Globals.Tags.GlobalDataItems)
   {
      if (gdi.Name == val) 
      { 
         text+= gdi.Value; 
      } 
   }
}
MessageBox.Show(text); // 102030
}

Upvotes: 0

Views: 75

Answers (2)

Martin
Martin

Reputation: 664

When you split spaces are supposed to be created in separate arrays because of the multiple separators provided. However, those are omitted because of the option StringSplitOptions.RemoveEmptyEntries you have given in Split.

Replace this option with StringSplitOptions.None. Now, just concatenate the every alternate array that contains empty string to the previous element in the array.

I have provided updated code below. See if this could help,

string[] values = headerData.Split(new string[] { "<#Tag(", ")>" }, StringSplitOptions.None);
string text = "";
string val1 = "";

var updatedValues = new List<string>();
for (int i = 0; i < values.Length; i++ )
{
    if(values[i] != string.Empty)
    {
        updatedValues.Add(values[i] + values[i + 1]);
        i++;
    }
}

foreach (string val in updatedValues) 
{
   foreach(GlobalDataItem gdi in Globals.Tags.GlobalDataItems)
   {
      if (gdi.Name == val) 
      { 
         text+= gdi.Value; 
      } 
   }
}
MessageBox.Show(text); // 102030
}

Upvotes: 1

woutervs
woutervs

Reputation: 1510

Set the split options to .None;

foreach(string val in values) {
if(string.IsNullOrWhiteSpace(val)) {
text+= val;
}
   foreach(GlobalDataItem gdi in Globals.Tags.GlobalDataItems)
   {
      if (gdi.Name == val) 
      { 
         text+= gdi.Value; 
      } 
   }
}

This should rebuild your old string. Another option would be to use a Regex and just replace the values.

Upvotes: 1

Related Questions