14 Replies - 829 Views - Last Post: 27 September 2012 - 08:08 AM Rate Topic: -----

#1 suskito  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 22-September 12

Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 06:48 PM

How can I iterate through a string and add the integers found along the way?
Let me explain:

String Input:
11111rqpst11111111rqq

Desired Output:
5rqpst8rqq

What I wish to accomplish:
To iterate through my input string. If I encounter a 1 then add all the 1's and keep iterating along the string. Again, if I encounter a group of 1's I add them together.

My code so far consists of the following:
           //I get the string from my textbox1
           String str = textBox1.Text;

           // Input string.
           string value = str;

           // I convert the string to an array to be able to iterate character by character
           char[] array = value.ToCharArray();

           // Loop through array.
           for (int i = 0; i < array.Length; i++)
           {
              
               // Get character from array.
               char letter = array[i];

               // Display each letter.
               String strLetter = letter.ToString();

               if (strLetter.Equals("1") || i < (array[i + 1].ToString().Equals("1"))
               {
                   {
                      //pseudo code which I cant seem to figure out how to put into code
              while char.next == 1
	      char = char.next
	      count + 1

	      if char.next != 1 then
		 textbo2.appendtext(count)
		
              //skip the already searched characters
	      i + count;
	      //reset count
              count = 1;
            }
                   
                   
               }
               else
               {
                   textBox2.AppendText(strLetter);
               }




Thank you!

Is This A Good Question/Topic? 0
  • +

Replies To: Iterate through String and add the value of any integers found?

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3479
  • View blog
  • Posts: 10,724
  • Joined: 05-May 12

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 07:13 PM

Let me suggest a different strategy. In pseudo code:
str = inputTextBox.Text;
sb = new StringBuilder();
i = 0;
while(i < str.Length)
{
    if (Char.IsDigit(str[i]))
    {
        int sum = 0;
        while (i < str.Length && Char.IsDigit(str[i]))
        {
            char value = str[i] - '0';
            sum += value;
            i++;
        }
        append the sum to the string builder
    }
    else
    {
        append str[i] to the string builder
    }
    i++;
}
final = sb.ToString();


Was This Post Helpful? 1
  • +
  • -

#3 November-06  Icon User is offline

  • D.I.C Regular

Reputation: 46
  • View blog
  • Posts: 391
  • Joined: 04-January 11

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 07:41 PM

Here is another solution:

            string strInput = "11111rqpst11111111rqq";
            string strOutput = string.Empty;
                        
            int intTotalNum = 0;
            bool hasNum = false; //Will be the condition in appending number

            for (int i = 0; i < strInput.Length; i++)
            {
                int intNum = 0;
                bool isNumeric = int.TryParse(strInput.Substring(i, 1), out intNum);
                if (isNumeric)
                {
                    intTotalNum += intNum;
                    hasNum = true;
                }
                else
                {
                    if (hasNum)
                        strOutput += intTotalNum.ToString();

                    strOutput += strInput.Substring(i, 1);
                    intTotalNum = 0;
                    hasNum = false;
                }
            }

            //In case there are numbers at the end of strInput
            if (hasNum)
                strOutput += intTotalNum.ToString();



The strOuput is the result you need.

I already tested this in Console Application. Hopefully, this is what you need.

This post has been edited by November-06: 25 September 2012 - 07:45 PM

Was This Post Helpful? 1
  • +
  • -

#4 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 08:18 PM

All lot problems can be solve by knowing previous and the current values.
string SumRunDigitsOfOne(string i)
{ var o= new System.Text.StringBuilder(i.Length);
  char p = null;
  int t = 0;
  foreach(var c in i)
  { if(c=='1'){ t++; }
    else { if( p=='1') 
           { o.Append(t.ToString());
             t=0;
           } else
           { o.Append(c);
           }          
         }
     p=c;
  }
  return o;
}


Was This Post Helpful? 1
  • +
  • -

#5 suskito  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 22-September 12

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 09:02 PM

View PostNovember-06, on 25 September 2012 - 07:41 PM, said:

Here is another solution:

            string strInput = "11111rqpst11111111rqq";
            string strOutput = string.Empty;
                        
            int intTotalNum = 0;
            bool hasNum = false; //Will be the condition in appending number

            for (int i = 0; i < strInput.Length; i++)
            {
                int intNum = 0;
                bool isNumeric = int.TryParse(strInput.Substring(i, 1), out intNum);
                if (isNumeric)
                {
                    intTotalNum += intNum;
                    hasNum = true;
                }
                else
                {
                    if (hasNum)
                        strOutput += intTotalNum.ToString();

                    strOutput += strInput.Substring(i, 1);
                    intTotalNum = 0;
                    hasNum = false;
                }
            }

            //In case there are numbers at the end of strInput
            if (hasNum)
                strOutput += intTotalNum.ToString();



The strOuput is the result you need.

I already tested this in Console Application. Hopefully, this is what you need.


Thank you all for your amazing support! You all have made my 5hrs of trying to figure it out worth every second!
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3479
  • View blog
  • Posts: 10,724
  • Joined: 05-May 12

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 10:40 PM

I recommend the use of a StringBuilder. Building up a string by using the '+=' or '+' operators of the string, or the Append() method of the string is slow, and will also eat up memory quickly.
Was This Post Helpful? 0
  • +
  • -

#7 November-06  Icon User is offline

  • D.I.C Regular

Reputation: 46
  • View blog
  • Posts: 391
  • Joined: 04-January 11

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 11:15 PM

View PostSkydiver, on 25 September 2012 - 10:40 PM, said:

I recommend the use of a StringBuilder. Building up a string by using the '+=' or '+' operators of the string, or the Append() method of the string is slow, and will also eat up memory quickly.


Following your advice, I revised the code to this:

            string strInput = "11111rqpst11111111rqq";
            StringBuilder strbOutput = new StringBuilder();
                        
            int intTotalNum = 0;
            bool hasNum = false; //Will be the condition in appending number

            for (int i = 0; i < strInput.Length; i++)
            {
                int intNum = 0;
                bool isNumeric = int.TryParse(strInput.Substring(i, 1), out intNum);
                if (isNumeric)
                {
                    intTotalNum += intNum;
                    hasNum = true;
                }
                else
                {
                    if (hasNum)
                        strbOutput.Append(intTotalNum.ToString());

                    strbOutput.Append(strInput.Substring(i, 1));
                    intTotalNum = 0;
                    hasNum = false;
                }
            }

            //In case there are numbers at the end of strInput
            if (hasNum)
                strbOutput.Append(intTotalNum.ToString());

            Console.Write(strbOutput.ToString());


This post has been edited by November-06: 25 September 2012 - 11:16 PM

Was This Post Helpful? 1
  • +
  • -

#8 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3479
  • View blog
  • Posts: 10,724
  • Joined: 05-May 12

Re: Iterate through String and add the value of any integers found?

Posted 25 September 2012 - 11:34 PM

On line 10, you are calling Substring() and then you do it again on line 21. That involves allocating two 1 character strings.

On line 19 and 29, the StringBuilder has an Append that takes an integer. There is no need to call ToString() which will again allocate another string.

And then on line 10, int.TryParse() is a really expensive way to find out if a single character is a numeric value. This is why in my pseudo code, I had used Char.IsDigit(). It didn't involve having to create a string merely for the purpose of testing to see if it's a number. And since you have a single character digit, my pseudo code also suggested just subtracting the ASCII character number of the '0' digit from the numeric digit that was found to figure out what the numeric value of that character was.
Was This Post Helpful? 0
  • +
  • -

#9 dotINSolution  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 16
  • Joined: 25-September 12

Re: Iterate through String and add the value of any integers found?

Posted 26 September 2012 - 12:28 AM

With the power of Regular Expressions and LINQ, here is my method of doing so:

private static string iterateAddition(string strOriginal)
        {
            // Loop a string and add all continous integer in the collection. dotINSolution
            foreach (Match m in Regex.Matches(strOriginal, @"\d+")
                                .OfType<Match>().Distinct()
                                .OrderByDescending(m => m.Value.Length))
            {
                int totalAddition = m.Value.Sum(c => int.Parse(c.ToString()));
                strOriginal = strOriginal.Replace(m.Value, totalAddition.ToString());
            }
            return strOriginal;
        }


Working Code:
Posted Image
Was This Post Helpful? 0
  • +
  • -

#10 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1377
  • View blog
  • Posts: 3,031
  • Joined: 05-April 11

Re: Iterate through String and add the value of any integers found?

Posted 26 September 2012 - 01:14 AM

You could make the code highly readable and short by using the Regex class.
I see that dotINSolution has tried to use the regex class to solve the problem, but I would do it completly different

        public Program() {
            string input = "11111rqpst11111111rqq";
            input = Regex.Replace(input, @"\d+", StringToInt);
            Console.WriteLine(input);
        }

        private string StringToInt(Match match) {
            int value = 0;
            foreach (char digit in match.Value)
                value += digit - '0';
            return value.ToString();
        }


Was This Post Helpful? 0
  • +
  • -

#11 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Iterate through String and add the value of any integers found?

Posted 26 September 2012 - 08:12 AM

View PostdotINSolution, on 26 September 2012 - 08:28 AM, said:

With the power of Regular Expressions and LINQ, here is my method of doing so:

private static string iterateAddition(string strOriginal)
        {
            // Loop a string and add all continous integer in the collection. dotINSolution
            foreach (Match m in Regex.Matches(strOriginal, @"\d+")
                                .OfType<Match>().Distinct()
                                .OrderByDescending(m => m.Value.Length))
            {
                int totalAddition = m.Value.Sum(c => int.Parse(c.ToString()));
                strOriginal = strOriginal.Replace(m.Value, totalAddition.ToString());
            }
            return strOriginal;
        }


Working Code:


Why are you doing the following?
  .OfType<Match>().Distinct()
  .OrderByDescending(m => m.Value.Length))


Could you explain further? As I can't see the sense of do it.

This post has been edited by AdamSpeight2008: 26 September 2012 - 08:14 AM

Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Re: Iterate through String and add the value of any integers found?

Posted 26 September 2012 - 11:36 AM

I'm guessing the OfType is to get an IEnumerable<Match>, since the result of Regex.Matches is a MatchCollection, which implements IEnumerable, not IEnumerable<T>.
Was This Post Helpful? 0
  • +
  • -

#13 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Iterate through String and add the value of any integers found?

Posted 26 September 2012 - 12:55 PM

It was more rest of that doesn't make sense.
Was This Post Helpful? 0
  • +
  • -

#14 dotINSolution  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 16
  • Joined: 25-September 12

Re: Iterate through String and add the value of any integers found?

Posted 27 September 2012 - 02:50 AM

View PostAdamSpeight2008, on 26 September 2012 - 08:12 AM, said:

View PostdotINSolution, on 26 September 2012 - 08:28 AM, said:

With the power of Regular Expressions and LINQ, here is my method of doing so:

private static string iterateAddition(string strOriginal)
        {
            // Loop a string and add all continous integer in the collection. dotINSolution
            foreach (Match m in Regex.Matches(strOriginal, @"\d+")
                                .OfType<Match>().Distinct()
                                .OrderByDescending(m => m.Value.Length))
            {
                int totalAddition = m.Value.Sum(c => int.Parse(c.ToString()));
                strOriginal = strOriginal.Replace(m.Value, totalAddition.ToString());
            }
            return strOriginal;
        }


Working Code:


Why are you doing the following?
  .OfType<Match>().Distinct()
  .OrderByDescending(m => m.Value.Length))


Could you explain further? As I can't see the sense of do it.

For OfType, Curtis Rutland has explained well. Distinct so that the same code is not ran twice with same value.
As for OrderByDescending, its because so that it replaces the largest value first then the shorter ones.
Eg as in OP:
"11111rqpst11111111rqq"
If 11111 would be replaced first, it will also modify string to: "5rqpst5111rqq", so next match won't replace it correctly.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3479
  • View blog
  • Posts: 10,724
  • Joined: 05-May 12

Re: Iterate through String and add the value of any integers found?

Posted 27 September 2012 - 08:08 AM

Ouch! So although the Regular Expression + LINQ version looks short and sweet, it is actually less efficient because:
- a state machine needs to built and compiled to parse the regular expression
- the matches need to be sorted
- multiple intermediate strings are created as each of the runs of integers are replaced
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1