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

Page 1 of 1

## 14 Replies - 1176 Views - Last Post: 27 September 2012 - 08:08 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=293231&amp;s=448190193f9a1a0b5043620a9cdd5733&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 suskito

Reputation: 0
• 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)

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

• Code herder

Reputation: 4260
• Posts: 13,632
• 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();

```

### #3 November-06

• D.I.C Regular

Reputation: 47
• Posts: 449
• 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

• MrCupOfT

Reputation: 2292
• Posts: 9,531
• 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;
}

```

### #5 suskito

Reputation: 0
• 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

November-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!

### #6 Skydiver

• Code herder

Reputation: 4260
• Posts: 13,632
• 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.

### #7 November-06

• D.I.C Regular

Reputation: 47
• Posts: 449
• Joined: 04-January 11

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

Posted 25 September 2012 - 11:15 PM

Skydiver, 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.

```            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

### #8 Skydiver

• Code herder

Reputation: 4260
• Posts: 13,632
• 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.

### #9 dotINSolution

Reputation: 6
• 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()));
}
return strOriginal;
}
```

Working Code:

### #10 CasiOo

• D.I.C Lover

Reputation: 1510
• Posts: 3,357
• 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();
}

```

• MrCupOfT

Reputation: 2292
• Posts: 9,531
• Joined: 29-May 08

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

Posted 26 September 2012 - 08:12 AM

dotINSolution, 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()));
}
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

### #12 Curtis Rutland

• （╯°□°）╯︵ (~ .o.)~

Reputation: 4832
• Posts: 8,611
• 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>.

• MrCupOfT

Reputation: 2292
• Posts: 9,531
• 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.

### #14 dotINSolution

Reputation: 6
• 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

AdamSpeight2008, on 26 September 2012 - 08:12 AM, said:

dotINSolution, 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()));
}
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.

### #15 Skydiver

• Code herder

Reputation: 4260
• Posts: 13,632
• 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