Is there a method that will remove a set amount of characters from a string, placing the removed characters into a separate string and leaving the original x amount of characters shorter?
I need to parse a string into 10 individual strings, each 10 characters long. I would like to be able to do sommething simple like this, but I do not know if there is a method that works like this in C#
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.removeFromSubstring(0, 10);
}
You could try this:
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(0, 10);
retrievedMessage = retrievedMessage.Substring(10);
}
The line retrievedMessage = retrievedMessage.Substring(10); will effectively remove the first 10 characters from the original string. This way in each iteration you will be able to use the first 10 characters and assign them to the errorCodes[i]
Also you could try to avoid using substrings:
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(i*10, 10);
}
Edit
Now tested, seems to work fine for me
var errorCodes = "longstringgggggggggggggggggggggggggg";
var count = 10;
List<string> s = new List<string>();
for (int i = 0; i < errorCodes.Length; i += count)
{
if (i + count > errorCodes.Length)
count = errorCodes.Length - i;
s.Add(errorCodes.Substring(i, count));
}
foreach (var str in s)
Console.WriteLine(str);
Console.ReadLine();
This should work for you
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
errorCodes[i] = retrievedMessage.Substring(10*i, 10);
}
Here is an option that will remove from the string retrievedMessage
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
//option to remove from string
errorCodes[i] = retrievedMessage.Substring(0, 10);
retrievedMessage = retrievedMessage.Remove(0,10); //will remove from string
}
Same basic concept as other answers but with a little checking for variable string length. If you know that your string is always 100 chars in length, then use one of the simpler answers.
string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
int startIndex = i * 10;
if (retrievedMessage.Length > startIndex)
{
int length = 10;
if (retrievedMessage.Length < (startIndex + length))
{
length = retrievedMessage.Length - startIndex;
}
errorCodes[i] = retrievedMessage.Substring(startIndex, length);
}
}
Note: Since errorCodes is always instantiated with a length of 10, this will have null strings if the length of retrievedMessage is <= 90. If you expect variable length, better to use a List<string> than a string[].
Related
So I actually have most of the code thought up myself and got it working last week, but just now I accidentally deleted it so here I am re-writing!
The logic goes, I have a TIN number for input, I want to split this every 3rd digit to neatly fit a physical form I have prepared. To do this, I iterate through the input, modulus by 3, place my delimiter a space, then split it by the delimiter.
So, the following 1234567891012 becomes 123 456 789 1012.
string input = txtTIN.Text;
string digit1 = "0";
string digit2 = "0";
string digit3 = "0";
string digit4 = "0";
StringBuilder sb = new StringBuilder();
for (int i = 1; i < input.Length; i++)
{
if (i%3 == 0)
{
sb.Append(' ');
sb.Append(input[i]);
}
}
string formatted = sb.ToString();
Console.WriteLine(formatted);
string[] formatCollection = formatted.Split(' ');
digit1 = formatCollection[0];
digit2 = formatCollection[1];
digit3 = formatCollection[2];
digit4 = formatCollection[3];
I realize now that I post it here that there seems to be something wrong with the string building, as a Console write is returning 1 4 7 out of the input. Not a desired result, but if I remember correctly, all of the pieces are already in place.
(Note, I do not want to use Linq, Regex, or Lists even though I know they are better alternatives. I thought this one up myself and want to see it work in the end.)
Also, how do I make it so that an input of 123456789101251 becomes 123 456 789 101251, in other words, i do not want to split any further than the first 3, something my current code fails to do.
There are couple of issues with your code
You start your iteration with 1, not 0.
You add a space at the beginning of your result.
You are only adding the first characters of each group.
You don't stop grouping even when your max amount of groups is reached.
This would address your issues:
const int GROUP_LENGTH = 3;
const int GROUP_COUNT = 3;
const int MAX_GROUPED_LENGTH = GROUP_LENGTH * GROUP_COUNT;
int groupedLength = Math.Min(input.Length, MAX_GROUPED_LENGTH);
for (int i = 0; i < groupedLength; i++)
{
if ((i > 0) && ((i % GROUP_LENGTH) == 0))
{
sb.Append(' ');
}
sb.Append(input[i]);
}
if (input.Length > MAX_GROUPED_LENGTH)
{
sb.Append(' ');
sb.Append(input, MAX_GROUPED_LENGTH, input.Length - MAX_GROUPED_LENGTH);
}
int size = 3; //size of the chunk
int count = 3; //how many sized chunks will be splitted
int length = input.Length / size;
int iterate = length < count ? length : count;
int tailLength = input.Length - iterate * size;
for (int i = 0; i < iterate; i++)
{
sb.Append(input.Substring(i, size));
sb.Append(' ');
}
if (tailLength > 0)
{
sb.Append(input.Substring(size * iterate, tailLength));
}
The code to add the digits int he string is in the wrong place. You are only adding the number to the string if it is index mod 3 is 0
for (int i = 1; i < input.Length; i++)
{
sb.Append(input[i]);
if (i%3 == 0)
{
sb.Append(' ');
}
}
string[] result = new string[4];
int groups = input.Length / 3;
if (groups > 3) groups = 3;
int group;
for (group = 0; group < groups; group++)
{
result[group] = input.Substring(group*3, 3);
}
// Assert: group < 4
result[group] = input.Substring(group*3);
// Assert: answers in result[0..groupCount-1]
int groupCount = group+1;
If you really don't want to use LINQ, i would propose to modify your algorithm this way:
StringBuilder sb = new StringBuilder();
StringBuilder partBuilder = new StringBuilder();
int partsSplitted = 0;
for (int i = 1; i <= input.Length; i++)
{
partBuilder.Append(input[i-1]);
if (i % 3 == 0 && partsSplitted<=3)
{
sb.Append(' ');
sb.Append(partBuilder.ToString());
partBuilder = new StringBuilder();
partsSplitted++;
}
}
sb.Append(partBuilder.ToString());
string formatted = sb.ToString().TrimStart();
With output:
123 456 789 101251
The changed to your idea are minimal and entire loop is the same. Please notify: your for loop should go till i <= input.Length not i < input.Length because you are starting with index 1, not 0.
Could downvoters explain what is wrong with accepted answer?
I am trying to generate a random alphanumeric array that consist of 3 letters and 6 digits. The entire array must be random. The only way I could think of is generating 2 individual random arrays and then merging them and randomizing the merged array. Any help would be appreciated. I specifically need help on ensuring that the correct number of variable types are stored. Here is my semi-working code:
static void Main(string[] args)
{
var alphabetic = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numeric = "0123456789";
var stringChars = new char[9];
var random = new Random();
for (int i = 0; i < 3; i++)
{
stringChars[i] = alphabetic[random.Next(alphabetic.Length)];
}
for(int i = 3; i< stringChars.Length; i++)
{
stringChars[i] = numeric[random.Next(numeric.Length)];
}
var ranChars = new char[9];
var semisorted = new String(stringChars);
for (int i=0; i< ranChars.Length; i++)
{
ranChars[i] = semisorted[random.Next(semisorted.Length)];
}
var final = new string(ranChars);
Console.WriteLine("{0}", final);
Console.ReadLine();
}
You're close. But the problem here is that you're selecting randomly from the "semi-sorted" array, while what's really necessary at that point is picking a random permutation. One way to do that is with a Fisher-Yates shuffle.
So combining that with the code you had that worked: (not tested)
for (int i = 0; i < 3; i++)
{
stringChars[i] = alphabetic[random.Next(alphabetic.Length)];
}
for(int i = 3; i< stringChars.Length; i++)
{
stringChars[i] = numeric[random.Next(numeric.Length)];
}
int n = stringChars.Length;
while (n > 1)
{
int k = random.Next(n--);
char temp = stringChars[n];
stringChars[n] = stringChars[k];
stringChars[k] = temp;
}
string result = new string(stringChars);
Harold's answer is way cleaner, but here's another approach for the whole '100 ways to do the same thing in programming' concept. [Edit: Doh, I reversed the number of digits and letters. Here's a fix:]
public static void Main(string[] args)
{
var random = new Random();
var finalString = string.Empty;
var finalArray = new string[9];
for (var i = 0; i < 3; i++)
{
var alphabet = random.Next(0, 26);
var letter = (char) ('a' + alphabet);
finalArray[i] = letter.ToString().ToUpper();
}
for (var i = 3; i < 9; i++)
{
var number = random.Next(0, 9);
finalArray[i] = number.ToString();
}
var shuffleArray = finalArray.OrderBy(x => random.Next()).ToArray();
for (var i = 0; i < finalArray.Length; i++)
{
finalString += shuffleArray[i];
}
Console.WriteLine(finalString);
Console.ReadKey();
}
I would like to create an array of an array from a text file...
There are 20000 line with 21 strings in each line separated by ',' .
I would like to read each line and make it into an array , each line being a new array within.
So I wanted to create the jagged array by starting it like this:
string[][] SqlArray = new string[200000][21];
But it gives: ERROR MESSAGE : Invalid rank specifier: expected ',' or ]
How would I create this array or initialize it?
I will be populating the data in the array like this:
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
for (int i = 0; i < workingArray.Length; i++)
{
for (int k = 0; k < 20; k++)
{
SqlArray[i][k] = workingArray[k];
}
}
}
Thank you
That type of initialization only works in Java. You must declare an array of arrays then initialize each in a loop.
string[][] SqlArray = new string[21][];
for(int index = 0; index < SqlArray.Length; index++)
{
SqlArray[index] = new string[2000000];
}
Alternatively, you can use a non-jagged array. It will probably work for what you need.
string[,] SqlArray = new string[21 , 2000000];
It can be accessed like so:
SqlArray[2,6264] = x;
To anyone who is interested this is how I ended up implementing it:
TextReader readIn = File.OpenText("..\\..\\datafile.txt");
string[][] SqlArray = new string[rowNumCreate][];
int e = 0;
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
SqlArray[e] = new string[valuesInRow +1];
for (int k = 0; k < workingArray.Length; k++)
{
SqlArray[e][k] = workingArray[k];
}
e++;
}
The file being read is a simple mock database set as a flat file that was auto-generated to test an algorithm that I am implementing, which works with jagged arrays; hence instead of working with a data base I just created this for ease of use and to increase and decrease size at will.
Here is the code to build the text file:
Random skill_id;
skill_id = new Random();
// int counter =0;
string seedvalue = TicksToString();
int rowNumCreate = 200000;
int valuesInRow = 20;
string lineInFile = seedvalue;
string delimiter = ",";
for (int i = 0; i < rowNumCreate; i++)
{
for (int t = 0; t < valuesInRow; t++)
{
int skill = skill_id.Next(40);
string SCon = Convert.ToString(skill);
lineInFile += delimiter + SCon;
}
if (rowNumCreate >= i + 1)
{
dataFile.WriteLine(lineInFile);
lineInFile = "";
string userPK = TicksToString();
lineInFile += userPK;
}
}
dataFile.Close();
public static string TicksToString()
{
long ms = DateTime.Now.Second;
long ms2 = DateTime.Now.Millisecond;
Random seeds;
seeds = new Random();
int ran = seeds.GetHashCode();
return string.Format("{0:X}{1:X}{2:X}", ms, ms2, ran).ToLower();
}
I am still a student so not sure if the code is A-grade but it works :)
I have a char array like this:
char[] true_false = new char[2]{'V','F'};
A variable random:
Random rand = new Random();
I have a string called generate_code, with the initial value is true_false[rand.Next(0, 2)].ToString();
string generate_code = true_false[rand.Next(0, 2)].ToString();
And the user will set the int lenght_of;
int lenght_of = int.Parse(Console.ReadLine());
So, what I am trying to do is: the user will define the lenght_of that will be the lenght of the generate_code like this:
for(int i =0; i < lenght_of;i++){
generate_code = generate_code + (char)true_false[rand.Next(0, 2)];
}
But the problem is that I need a fixed variable like :
generate_code = (char)true_false[rand.Next(0, 2)] + (char)true_false[rand.Next(0, 2)];
if lenght_of =2; and I have a loop that will change the generate_code value ten times.How can I do that? **I hope that u guys understand it is hard to explain.
Example:
lenght_of = 2;
//Example "FF";
generate_code = true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)];
for(int i =0; i < 10;i++) {
Console.WriteLine(generate_code);
} //Output expected: "FF" "VV" "FV" "VF" "FF"
Your problem is that you're adding two char's together. char is a numeric type.. therefore you're getting numbers as the result. Also, your generate_code assignment must be inside your loop:
for(int i =0; i < 10;i++) {
generate_code = string.Format("{0}", generateCodeWithLength(rand, true_false, lenght_of));
Console.WriteLine(generate_code);
}
Wrap the code generation in a method that accepts the length:
public string generateCodeWithLength(Random rand, char[] true_false, int length) {
var result = new StringBuilder(length);
for (var i = 0; i < length; i++) {
result.Append(true_false[rand.Next(0, 2)]);
}
return result.ToString();
}
Or better yet.. a StringBuilder. Clicky clicky live example.
Alternatively you can also do something like:
for(int i =0; i < 10;i++) {
Console.WriteLine(string.Format("{0}{1}", true_false[rand.Next(0, 2)] + true_false[rand.Next(0, 2)]));
}
You need to refresh generate_code in each iteration of the loop:
for(int i =0; i < 10;i++) {
int loopCounter = 0;
while (loopCounter < length_of)
{
generate_code += true_false[rand.Next(0, 2)]; //Add one more char to generate_code
loopCounter += 1;
}
Console.WriteLine(generate_code);
} //Output expected if length_of = 3: "FFV" "VFV" "FVF" "FFF" "VVV"
That way, each output will be random.
string[] myString = {"a","b","c","d"}
//Reverse string algorithm here
myString = {"d","c","b","a"}
I have been asked to do so in an interview without the help of any temporary variable or .NET class, string methods, etc to reverse the elements of the same string array. I was told to use basic programming constructs like loops. Since, I am up for another interview today, I am in a hurry to know whether this is actually possible because I could not find a solution to this.
Here you go, no support variables, no .net functions :) But it makes the assumptions that all the strings in the array have length 1 ( as they do in the code you posted).
string[] myString = {"a","b","c","d", "e"};
for(int i = 0; i < myString.Length/2; i++)
{
myString[i] += myString[myString.Length -1 -i];
myString[myString.Length -1 -i] = ""+myString[i][0];
myString[i] = "" + myString[i][1];
}
Since you cannot use a temporary variable, the best I can think of is appending the strings first and then removing the appended part again:
// append last strings to first strings
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i] + myString[myString.Length - i - 1];
}
// copy first half to last half
for(int i = myString.Length / 2 + 1; i < myString.Length; i++)
{
myString[i] = myString[myString.Length - i - 1]
.SubString(0,
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
// remove useless part from first half
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i].SubString(
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
Stupid approach? Yes. But no additional variables are involved.
string[] myString = {"a","b","c","d"}
for(int = (myString.Length - 1); int >= 0; i--) {
string rev = myString[i];
Console.Write(rev);
}
Sorry I posted a wrong answer... here's the verified one:
int k = len - 1;
for(int i = 0; i<len/2; i++)
{
myString[i] = myString[i]+"."+myString[k--];
}
for(int i = len/2; i<len; i++)
{
myString[i] = myString[k].substring(0, 1);
myString[k] = myString[k--].substring(2,3);
}
However, just consider this a pseudo-code... I did not check for .NET syntax.
The right answer in your interview is "Why would you NOT use the class libraries?" But then say, "Well if I needed to write a customized method because the libraries don't support the need...". Then I would show both methods and argue when to use each method. If they had a problem with this explanation then I wouldn't want to work there anyway.
With Libraries:
string[] myString = {"a","b","c","d"};
List<string> list = myString.ToList();
list.Reverse();
myString = list.ToArray();
Without:
string[] myString = {"a","b","c","d"};
string[] newString = new string[myString.Length];
for (int i = 0, j = myString.Length - 1; i < myString.Length && j >= 0; i++, j--)
{
newString[j] = myString[i];
}
myString = newString;
This is not a complete answer, perhaps an idea..
It is possible to swap two numbers by mathematics
swap(a,b)
a = a + b
b = a - b
a = a - b
Initially I was going to suggest this can be done with character ascii values.. Then I noticed the strings.
Is it acceptable then to
swap(str1, str2)
str1 = str1+str2
str2 = str1[0]
str1 = str1[1]
I hope you get the idea
Have you tried this
string[] myString = { "a", "b", "c", "d","e","f" };
int _firstcounter = 0;
int _lastcounter = myString.Length-1;
while (_firstcounter<=_lastcounter)
{
myString[_firstcounter] += myString[_lastcounter];
myString[_lastcounter] = "" + myString[_firstcounter][0];
myString[_firstcounter] = "" + myString[_firstcounter][1];
_firstcounter++;
_lastcounter--;
}
If the maximum string length is of array is less than 10, then is might be helpful....
string[] myString = { "aaaa", "bbb", "ccccccc", "dddddd", "e", "fffffffff" };
for (int i = 0; i < myString.Length; i++)
{
myString[i] = myString[i].Length.ToString() + myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i] + myString[myString.Length-1-i];
myString[myString.Length - 1 - i] = myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i].Substring(int.Parse(myString[i][0].ToString())+2,int.Parse(myString[i][int.Parse(myString[i][0].ToString())+1].ToString()));
}
for (int i = myString.Length / 2; i < myString.Length; i++)
{
myString[i] = myString[i].Substring(1, int.Parse(myString[i][0].ToString()));
}
Try this.
public static class ExtensionMethods
{
public static IEnumerable<T> ReverseArray<T>(this T[] source)
{
for (int i = source.Length - 1; i >= 0; i--)
{
yield return source[i];
}
}
public static T[] EnumerableToArray<T>(this IEnumerable<T> source)
{
var array = new T[source.Count()];
int k = 0;
foreach (var n in source)
{
array[k++] = n;
}
return array;
}
}
Example usage
public static void Main(string[] args)
{
string[] myString = {"a", "b", "c", "d"};
myString = myString.ReverseArray().EnumerableToArray();
}
static void ReverseMyString(string[] myString)
{
int start=0, end= myString.Length-1;
string temp = "";
while (start < end)
{
temp = myString[start];
myString[start] = myString[end];
myString[end] = temp;
start++;
end--;
}
}
Yes you can do it-
string[] myString = { "a", "b", "c", "d" };
myString = (from a in myString orderby a descending select a).ToArray();
You need at least one variable to swap values.
In pseudo code:
for(i : 0..n/2) {
// swap s[i] and s[n-i]
String tmp = s[i];
s[i] = s[n-i];
s[n-i] = tmp;
}
We Can use Array.Reverse(UrArray);
Check out Array.Reverse method on MSDN.