How to add symbols automatically in c#? - c#

I'm beginning programming with C# and have a question:
I have a string of character like abcdef123456789. But the string is too long, therefore I want to add : automatically, after the second, fourth, six .... symbol.
How can I do that?

There is no built in method that does something like that. You just have to put the separators in there by looping through the string.
You can loop though the characters and put them in a StringBuilder, adding a colon at every other character:
string input = "abcdef123456789";
StringBuilder builder = new StringBuilder();
int cnt = 0;
foreach (char c in input) {
if (cnt == 2) {
builder.Append(':');
cnt = 0;
}
builder.Append(c);
cnt++;
}
string output = builder.ToString();

You could try this approach. I've attempted to make it as readable as possible, so hopefully it makes sense to you.
var s = "abcdef123456789";
var charsChanged = new List<char>();
for (var i = 0; i < s.Length; i++)
{
charsChanged.Add(s[i]);
var evenCharacter = i % 2 != 0;
var atEndOfString = i == s.Length - 1;
if (evenCharacter && !atEndOfString)
{
charsChanged.Add(':');
}
}
var updatedString = string.Concat(charsChanged));
updatedString will equal ab:cd:ef:12:34:56:78:9.
This approach makes use of the modulus operator (%) to determine if we're at an even or odd character. For more examples, check this out.

You can use a StringBuilder and do something like this:
string sourceStr = "123456789";
StringBuilder s = new StringBuilder();
foreach(char c in sourceStr){
s.append(c);
s.append(":");
}

Related

remove string between "|" and "," in stringbuilder in C#

I use VS2019 in Windows7.
I want to remove string between "|" and "," in a StringBuilder.
That is , I want to convert StringBuilder from
"578.552|0,37.986|317,38.451|356,23"
to
"578.552,37.986,38.451,23"
I have tried Substring but failed, what other method I could use to achieve this?
If you have a huge StringBuilder and that's why converting it into String and applying regular expression is not the option,
you can try implementing Finite State Machine (FSM):
StringBuilder source = new StringBuilder("578.552|0,37.986|317,38.451|356,23");
int state = 0; // 0 - keep character, 1 - discard character
int index = 0;
for (int i = 0; i < source.Length; ++i) {
char c = source[i];
if (state == 0)
if (c == '|')
state = 1;
else
source[index++] = c;
else if (c == ',') {
state = 0;
source[index++] = c;
}
}
source.Length = index;
StringBuilder isn't really setup for much by way of inspection and mutation in the middle. It would be pretty easy to do once you have a string (probably via a Regex), but StringBuilder? not so much. In reality, StringBuilder is mostly intended for forwards-only append, so the answer would be:
if you didn't want those characters, why did you add them?
Maybe just use the string version here; then:
var s = "578.552|0,37.986|317,38.451|356,23";
var t = Regex.Replace(s, #"\|.*?(?=,)", ""); // 578.552,37.986,38.451,23
The regex translation here is "pipe (\|), non-greedy anything (.*?), followed by a comma where the following comma isn't part of the match ((?=,)).
If you don't know very much of Regex patterns, you can write your own custom method to filter out data; its always instructive and a good practicing exercise:
public static String RemoveDelimitedSubstrings(
this StringBuilder s,
char startDelimitter,
char endDelimitter,
char newDelimitter)
{
var buffer = new StringBuilder(s.Length);
var ignore = false;
for (var i = 0; i < s.Length; i++)
{
var currentChar = s[i];
if (currentChar == startDelimitter && !ignore)
{
ignore = true;
}
else if (currentChar == endDelimitter && ignore)
{
ignore = false;
buffer.Append(newDelimitter);
}
else if (!ignore)
buffer.Append(currentChar);
}
return buffer.ToString();
}
And youd obvisouly use it like:
var buffer= new StringBuilder("578.552|0,37.986|317,38.451|356,23");
var filteredBuffer = b.RemoveDelimitedSubstrings('|', ',', ','));

Concatenating two strings into a Textbox

I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.
All this method does is combining the entire sentence and give them index starting from zero.
it then separates the even indexed characters into an array and the odd ones into a different array .
When I convert the two arrays to strings and then place them in a textbox only the first string shows up.
private void ZigzagBu_Click(object sender, EventArgs e) {
string s = PlaintextTB.Text;
s = s.Replace(" ","");
char[] whole = s.ToCharArray();
char[] even = new char[whole.Length];
char[] odd = new char[whole.Length];
int evenIndex = 0;
int oddIndex = 0;
for(int i =0;i<whole.Length;i++) {
if (i % 2 == 0) {
even[evenIndex] = whole[i];
evenIndex++;
}
else {
odd[oddIndex] = whole[i];
oddIndex++;
}
}
s = new String(even);
string m = new String(odd);
CiphertextTB.Text = s+m;
}
The problem was in the size of the char arrays. I solved it by <br/>
char[] even = new char[whole.Length/2];
char[] odd = new char[whole.Length/2];
Actually, your code is over complicated.
The same thing can be done with simple strings, no need to convert to char arrays:
var s = "0123456";
var even = "";
var odd = "";
for(int i=0; i<s.Length;i++)
{
if(i % 2 == 0)
{
even += s[i];
}
else
{
odd += s[i];
}
}
var result = even + odd;
However, if your plain text string is even a bit long (say, 10, 20 chars) - a better implementation would be to use StringBuilder:
var s = "0123456";
var even = new StringBuilder();
var odd = StringBuilder();
for(int i=0; i<s.Length;i++)
{
if(i % 2 == 0)
{
even.Append(s[i]);
}
else
{
oddAppend(s[i]);
}
}
var result = even.Append(odd.ToString()).ToString();
Use of StringBuilder class is more elegant approach instead of creating 2 instances of String.
Implementation: DotnetFiddler

Stringbuilder adds backslash after converting it to string

I have a situation in which I want to add inverted commas the the string.
static void Main(string[] args)
{
int valueCounter = 0;
int valueCount = 0;
var valueBuilder = new StringBuilder();
List<string> values = new List<string>();
values.Add("AAAA");
values.Add("BBBB");
values.Add("CCCC");
valueCount = values.Count;
foreach (var value in values)
{
valueCounter++;
if ((valueCounter - 1) > 0)
valueBuilder.Append("\"");
valueBuilder.Append(values[valueCounter - 1].ToString());
if (valueCounter != valueCount)
{
valueBuilder.Append(#",");
}
}
string output = valueBuilder.ToString();
}
As you can see, after converting the Stringbuilder to string, it adds the backslash to the string.
Please help me to know how I can get the desired out as : "AAAA","BBBB", "CCCC"
Here are the corrected version of your code (fixed enclosing of the first fragments):
string[] strArr = new string[] {
"AAAA", "BBBB","CCCC"
};
StringBuilder sb = new StringBuilder();
for(int i = 0; i < strArr.Length; i++) {
sb.Append('"');
sb.Append(strArr[i]);
sb.Append('"');
if(i < strArr.Length - 1)
sb.Append(',');
}
var output = sb.ToString();
This is how the debugger displays result (quoted/escaped view):
This is how it looks in human-readable format:
"AAAA","BBBB","CCCC"
Tips&tricks:
You can use the nq format-specifier to display string unquoted/unescaped:
output,nq
I think the following code for foreach loop will solve your problem.
foreach (var value in values)
{
value = "\""+value+"\"";
valueBuilder.Append(value);
if (++valueCounter != valueCount)
{
valueBuilder.Append(#",");
}
}
The use of quotation marks in a Java String object must be escaped. The \ you are complaining about is only visible in your tool and is required to escape the " so that no error occurs. If you were to perform a System.out.println(output); you will not see the \ character.
Just remove valueBuilder.Append("\"");
My mistake. It does just escape the \

C# Concatenate strings or array of chars

I'm facing a problem while developing an application.
Basically,
I have a fixed string, let's say "IHaveADream"
I now want to user to insert another string, for my purpose of a fixed length, and then concatenate every character of the fixed string with every character of the string inserted by the user.
e.g.
The user inserts "ByeBye"
then the output would be:
"IBHyaevBeyAeDream".
How to accomplish this?
I have tried with String.Concat and String.Join, inside a for statement, with no luck.
One memory-efficient option is to use a string builder, since both the original string and the user input could potentially be rather large. As mentioned by Kris, you can initialize your StringBuilder capacity to the combined length of both strings.
void Main()
{
var start = "IHaveADream";
var input = "ByeBye";
var sb = new StringBuilder(start.Length + input.Length);
for (int i = 0; i < start.Length; i++)
{
sb.Append(start[i]);
if (input.Length >= i + 1)
sb.Append(input[i]);
}
sb.ToString().Dump();
}
This only safely accounts for the input string being shorter or equal in length to the starting string. If you had a longer input string, you'd want to take the longer length as the end point for your for loop iteration and check that each array index is not out of bounds.
void Main()
{
var start = "IHaveADream";
var input = "ByeByeByeByeBye";
var sb = new StringBuilder(start.Length + input.Length);
var length = start.Length >= input.Length ? start.Length : input.Length;
for (int i = 0; i < length; i++)
{
if (start.Length >= i + 1)
sb.Append(start[i]);
if (input.Length >= i + 1)
sb.Append(input[i]);
}
sb.ToString().Dump();
}
You can create an array of characters and then re-combine them in the order you want.
char[] chars1 = "IHaveADream".ToCharArray();
char[] chars2 = "ByeBye".ToCharArray();
// you can create a custom algorithm to handle
// different size strings.
char[] c = new char[17];
c[0] = chars1[0];
c[1] = chars2[0];
...
c[13] = chars1[10];
string s = new string(c);
var firstString = "Ihaveadream";
var secondString = "ByeBye";
var stringBuilder = new StringBuilder();
for (int i = 0; i< firstString.Length; i++) {
stringBuilder .Append(str[i]);
if (i < secondString.Length) {
stringBuilder .Append(secondStr[i]);
}
}
var result = stringBuilder.ToString();
If you don't care much about memory usage or perfomance you can just use:
public static string concatStrings(string value, string value2)
{
string result = "";
int i = 0;
for (i = 0; i < Math.Max(value.Length, value2.Length) ; i++)
{
if (i < value.Length) result += value[i].ToString();
if (i < value2.Length) result += value2[i].ToString();
}
return result;
}
Usage:
string conststr = "IHaveADream";
string input = "ByeBye";
var result = ConcatStrings(conststr, input);
Console.WriteLine(result);
Output: IBHyaevBeyAeDream
P.S.
Just checked perfomance of both methods (with strBuilder and simple cancatenation) and it appears to be that both of this methods take same time to execute (if you have just one operation). The main reason for it is that string builder take considerable time to initialize while with use of concatenation we don't need that.
But in case if you have to process something like 1500 strings then it's different story and string builder is more of an option.
For 100 000 method executions it showed 85 (str buld) vs 22 (concat) ms respectively.
My Code

How to delete every 2nd character in a string?

How to delete every 2nd character in a string?
For example:
3030313535333635 -> 00155365
3030303336313435 -> 00036145
3032323437353530 -> 02247550
The strings are always 16-characters long and the result is always 8 characters long - and the character that is being removed is always a '3' - Don't ask why however - I did not dream up this crazy source data.
Try this to get the every other character from the string:-
var s = string.Join<char>("", str.Where((ch, index) => (index % 2) != 0));
String input = "3030313535333635";
String result = "";
for(int i = 1; i < 16; i +=2 )
{
result += input[i];
}
You can use this well-known class System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary :)
string str = "3030313535333635";
var hex = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(str);
var newstr = Encoding.ASCII.GetString(hex.Value);
Using a StringBuilder to create a string will save resources
string input = "3030313535333635";
var sb = new StringBuilder(8); // Specify capacity = 8
for (int i = 1; i < 16; i += 2) {
sb.Append(input[i]);
}
string result = sb.ToString();
Code in Java Language
String input= "3030313535333635"
String output="";
for(int i=1;i<input.length();i=i+2)
{
output+=input.charAt(i).toString();
}
System.out.println(output);

Categories