hi,

I am trying to replace an integer in string or list...what i have done is to use foreach loop..but it wouldnt replace it. The whole idea is that i have few lines of string in list and want to find a line and replace the int with another int,,,

here is the code :

foreach (var linesInList in list)
                    {
                        foreach (var number in Number)
                        {
                            if (linesInList.Contains(number.Value))
                            {
                                myNumber = Int32.Parse(linesInList.Trim().Substring(0, linesInList.Trim().IndexOf(' ')));
                                linesInList.Replace(myNumber.ToString(), number.Key.ToString());
                            }
                        }

                    }

help would be appreciated.

Thanks

...just a string

string strData = "This string has 5 words";
Console.WriteLine(strData.Replace("5", "five"));

or two options:

using System;
using System.Collections.Generic;
using System.Linq;

namespace DW_398224
{
   class Program
   {
      static void Main(string[] args)
      {
         string strData = "This string has 5 words";
         Console.WriteLine(strData.Replace("5", "five"));

         List<string> lst_strData = 
            new List<string>() { "this", "string", "has", "5", "words" };

         lst_strData =
            string.Join(" ",
            lst_strData.ToArray())
            .Replace("5", "five")
            .Split(' ')
            .ToList();

         lst_strData.ForEach(s => Console.WriteLine(s));
      }
   }
}

Also, the non-LINQ method

int iDelete = lst_strData.IndexOf("5");
lst_strData.RemoveAt(iDelete);
lst_strData.Insert(iDelete, "five");

lst_strData.ForEach(s => Console.WriteLine(s));

So, even though I replaced the digits with words, you can understand where to replace them with other digits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.