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
Related
I need to reverse a string using a for loop but I just can't do it. What I'm doing wrong?
class Program
{
static void Main(string[] args)
{
string s;
string sReverse;
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = 0; i < s.Length; i++)
{
s[s.Length - i] = sReversa[i];
}
}
}
Strings are immutable. You can't change them character by character.
If you want random access to the characters in a string, convert it to a char array first (using ToCharArray), then convert it back when you're done (String has a constructor that accepts a char array).
string a = "1234";
char[] b = a.ToCharArray();
b[1] = 'X';
a = new string(b);
Console.WriteLine("{0}", a);
Output:
1X34
There are much easier ways to reverse a string (e.g. LINQ would let you do var output = new string(input.Reverse().ToArray());), but if you want to use a for loop and your current approach, this is probably the piece of information you are missing.
These will be the minimal changes required in your code:
public static void Main()
{
string s;
string sReverse = string.Empty; // Initialise (always recommended)
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0 ; i--) // Chnage the order of indexing
{
sReverse += s[i]; // makes a new string everytime since strings are immutable.
}
Console.WriteLine(sReverse); // print your new string
}
As others said this may not be the best approach for very large number of string manipulation / formation. Instead, use StringBuilder.
StringBuilder is suited in situations where you need to perform repeated modifications to a string, the overhead associated with
creating a new String object can be costly.
Below is the snippet on how to use StringBuilder:
using System;
using System.Text; // Add this for StringBuilder
public class Program
{
public static void Main()
{
string s;
StringBuilder sReverse = new StringBuilder(); // Instantiate the object.
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0 ; i--)
{
sReverse.Append(s[i]); // Keep Appending to original string.
}
Console.WriteLine(sReverse.ToString()); // finally convert to printable string.
}
}
string reverse = string.Join("", "some word".Reverse());
You can not use s[s.Length - i] = sReversa[i];
Because Strings are immutable.
Instead, you can use sReverse = sReverse + s[Length];
The following code will give you reverse of a string:
static void Main(string[] args)
{
string s;
string sReverse = "";
int Length;
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
Length = s.Length - 1;
for (int i = Length; i >= 0; i--)
{
sReverse = sReverse + s[Length];
Length--;
}
Console.WriteLine("{0}", sReverse);
Console.ReadLine();
}
Note: For a large number of iteration, this might be a performance issue.
The simplest way to make your code work with minimal changes is to use a StringBuilder. Unlike string a StringBuilder is mutable.
Here's the code:
Console.WriteLine("Say any word please: ");
string s = Console.ReadLine();
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < s.Length; i++)
{
sb[s.Length - i - 1] = s[i];
}
string r = sb.ToString();
If you must use a for loop the way you want, you will have to allocate a new char array, initialize it with the string's characters from back to front, then take advantage of the string constructor that takes a char array as input. The code looks as follows:
public static string ReverseWithFor(string s)
{
if (string.IsNullOrEmpty(s)) return s;
char[] a = new char[s.Length];
for (int i = 0; i < s.Length; i++)
a[s.Length - 1 - i] = s[i];
return new string(a);
}
I am doing this in this way but its remove string previous characters, its out put is (Magic,Agic,Gic,Ic,C) but I want the whole string to be concate before and after.
public string[] Transform(string st)
{
string[] arr = new string[st.Length];
string[] arr1 = new string[st.Length];
for (int x = 0; x < st.Length; x++)
{
arr1[x] = char.ToLower(st[x]) + "".ToString();
}
for (int i = 0; i < st.Length; i++)
{
string st1 = "";
{
st1 = char.ToUpper(st[i]) + st.Substring(i + 1);
}
arr[i] = st1;
}
return arr;
}
You can do this with a single loop:
public static string[] Transform(string str)
{
var strs = new List<string>();
var sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
sb.Clear();
sb.Append(str);
sb[i] = char.ToUpper(str[i]);
strs.Add(sb.ToString());
}
return strs.ToArray();
}
What this does is adds the str to a StringBuilder and then modifies the indexed character with the upper case version of that character. For example, the input abcde will give:
Abcde
aBcde
abCde
abcDe
abcdE
Try it out on DotNetFiddle
If you wanted to get really fancy I'm sure there is some convoluted LINQ that can do the same, but this gives you a basic framework for how it can work.
You forgot to add left part of the string. Try to do like this:
st1 = st.ToLower().Substring + char.ToUpper(st[i]) + st.Substring(i + 1);
Here. This is twice as fast as the method that uses a string builder and a List
public static string[] Transform(string str)
{
var strs = new string [str.Length];
var sb = str.ToCharArray();
char oldCh;
for (int i = 0; i < str.Length; i++)
{
oldCh = sb[i];
sb[i] = char.ToUpper(sb[i]);
strs[i] = new string (sb);
sb[i] = oldCh;
}
return strs;
}
There's no need to clear and keep reading the string to the string builder. We also know the size of the array so that can be allocated at the start.
I wrote an answer for your questions (it's second code snippet), you can modify it for your needs, like changing the return type to string[], or use ToArray() extension method if you wanna stick with it. I think it's more readable this way.
I decided to put a the end little profiler to check CPU usage and memory compared to #Ron Beyer answer.
Here is my first attempt:
public static void Main()
{
var result = Transform("abcde");
result.ToList().ForEach(WriteLine);
}
public static IEnumerable<string> Transform(string str)
{
foreach (var w in str)
{
var split = str.Split(w);
yield return split[0] + char.ToUpper(w) + split[1];
}
}
Result:
Abcde
aBcde
abCde
abcDe
abcdE
Code fiddle https://dotnetfiddle.net/gnsAGX
There is one huge drawback of that code above, it works only if the passed word has unique letters. Therefore "aaaaa" won't produce proper result.
Here is my second successful attempt that seems works with any string input. I used one instance of StringBuilder to decrease the number of objects that would need to be created and manage on one instance, instead of so much copying objects so it's more optimized.
public static void Main()
{
var result = Transform("aaaaa");
result.ToList().ForEach(WriteLine);
}
public static IEnumerable<string> Transform(string str)
{
var result = new StringBuilder(str.ToLower());
for( int i = 0; i < str.Length; i++)
{
result[i] = char.ToUpper(str[i]);
yield return result.ToString();
result[i] = char.ToLower(str[i]);
}
}
Result:
Aaaaa
aAaaa
aaAaa
aaaAa
aaaaA
Code fiddle: https://dotnetfiddle.net/tzhXtP
Measuring execute time and memory uses.
I will use dotnetfiddle.net status panel, to make it easier.
Fiddle has few limitations like time execution of code 10 sec and used memory
besides differences are very significant.
I tested programs with 14 000 repetitions, my code additionally changes the output to array[].
My answer (https://dotnetfiddle.net/1fLVw9)
Last Run: 12:23:09 pm
Compile: 0.046s
Execute: 7.563s
Memory: 16.22Gb
CPU: 7.609s
Compared answer (https://dotnetfiddle.net/Zc88F2)
Compile: 0.031s
Execute: 9.953s
Memory: 16.22Gb
CPU: 9.938s
It slightly reduces the execution time.
Hope this helps!
public static string[] Transform(string str)
{
var strs = new string [str.Length];
var sb = str.ToCharArray();
char oldCh;
for (int i = 0; i < str.Length; i++)
{
oldCh = sb[i];
sb[i] = char.ToUpper(sb[i]);
strs[i] = new string (sb);
sb[i] = oldCh;
}
return strs;
}
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
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(":");
}
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);