ConvertLettersInString

  • Thread starter Thread starter gh
  • Start date Start date
G

gh

I have a string of 20 characters. I would like to replace all the
letters, between the 3rd and 17th letters, with a Z. Is there a
function for this?

Thanks
 
No.

Depending upon what you want, you would have to code either:

string modified = original.Substring(0, 2) + "Z" + original.Length > 17
? original.Substring(17) : "";

or

StringBuilder sb = new StringBuilder(original.Substring(0,2));
for (int i = 2; i < Math.Min(17, original.Length); i++)
{
sb.Append("Z");
}
if (original.Length > 17)
{
sb.Append(original.Substring(17));
}
string modified = sb.ToString();

or something like that. :)
 
gh said:
I have a string of 20 characters. I would like to replace all the
letters, between the 3rd and 17th letters, with a Z. Is there a
function for this?

Thanks

Here's how I'd do it:

using System;
using System.Text;
using System.Text.RegularExpressions;

namespace regex {
class Program {
static void Main(string[] args) {

string a = "abcdefghij1234567890"; // 20 chars.

string b = Regex.Replace(
a, @"^(\w{3})(.{14})(\w{3})$", "$1ZZZZZZZZZZZZZZ$3"
);

Console.WriteLine("before: " + a);
Console.WriteLine("after : " + b);

}
}
}
 
gh said:
I have a string of 20 characters. I would like to replace
all the letters, between the 3rd and 17th letters, with a Z.
Is there a function for this?

Yes, you need to call the String.ReplaceThirdToSeventeenthWithZed()
method.

P.
 
Paul E Collins said:
Yes, you need to call the String.ReplaceThirdToSeventeenthWithZed()
method.

In the USA you need to use ReplaceThirdToSeventeenthWithZee() method
otherwise you will get an error 1776.

SP
 
Actually, if you want to use a StringBuilder, there is an overload of the
StringBuilder.Replace() method that takes an index and a count. Example:

StringBuilder sb = new StringBuilder("AAAAAAAAAAAAAAAAAAAA");
return sb.Replace(sb.ToString().Substring(3, 14),
"ZZZZZZZZZZZZZZ").ToString();
// returns "AAAZZZZZZZZZZZZZZAAA"

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 
Back
Top