I have an array of drive letters and I need to append a colon to each letter and then pass the array to another function. Can I do this or do I need to create a new array? Or maybe not an array at all but some kind of List instead?
string source = "C|D|E";
string[] sourcearray = source.Split('|');
foreach (string driveletter in sourcearray)
{
//need to append ":" to each drive letter
}
EDIT: There are times when the source array could end in a pipe:
string source = "C|D|E|";
When that happens the last element in the array will be a colon if I use a common for loop, and I can't have this. How best to handle this? When this happens the final array needs to look like:
C: D: E:
Thanks.
Strings are immutable, so you can't change the string instance but you must change the array slots with new strings:
string source = "C|D|E";
string[] sourcearray = source.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i < sourcearray.Length; i++)
{
sourcearray[i] = sourcearray[i] + ":";
}
Replace your for-loop with
string[] resultArray = sourcearray.Select(s => s + ":").ToArray();
Re the Edit:
string source = "C|D|E|";
The best solution here is to this is a special variation of the string.Split() method. Unfortunately that one requires an array of separator chars, so we get:
sourceArray = source.Split(new char[] {'|'},
StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < sourcearray.Length; i++)
{
sourceArray[i] += ":";
}
string[] sourcearray = source.Split('|').Select(s => s + ":").ToArray();
var newArray = source.Split('|').Select(s => s + ":").ToArray();
Related
I have a string which has multiple spaces between the words and I want to remove these spaces and then bring them back .. The problem was in bringing the spaces back after deleting them I tried to code my idea but it runs without any output and some times it gives me an exception of "Index was outside of array bounds" .. any help
string pt = "My name is Code"
int ptLenght = pt.Length;
char[] buffer1 = pt.ToCharArray();
spaceHolder = new int[pt.Length];
for (int m = 0; m < pt.Length; m++)
{
if (buffer1[m] == ' ')
{
hold = m;
spaceHolder[m] = hold;
}
}
char[] buffer = pt.Replace(" ", string.Empty).ToCharArray();
int stringRemovedSpaces = pt.Length;
char[] buffer = pt.ToCharArray(); // source
char[] buffer2 = new char[ptLenght]; // destination
for (int i = 0; i < pt.Length; i++)
{
buffer2[i] = buffer[i];
}
for (int i = 0; i < buffer2.Length; i++)
{
if (i == spaceHolder[i])
{
for (int m = stringRemovedSpaces; m <= i; m--)
{
buffer2[m-1] = buffer2[m];
}
buffer2[i] = ' ';
}
}
return new string(buffer2);
I suspect that you want to replace multiple spaces with a single one. The fastest and easiest way to do this is with a simple regular expression that replaces multiple whitespaces with a single space, eg:
var newString = Regex.Replace("A B C",#"\s+"," ")
or
var newString = Regex.Replace("A B C",#"[ ]+"," ")
The reason this is fastest than other methods like repeated string replacements is that a regular expression does not generate temporary strings. Internatlly it generates a list of indexes to matching items. A string is generated only when the code asks for a string value, like a match or replacement.
A regular expression object is thread-safe as well. You can create it once, store it in a static field and reuse it :
static Regex _spacer = new Regex(#"\s+");
public void MyMethod(string someInput)
{
...
var newString=_spacer.Replace(someInput, " ");
...
}
Deleting all the spaces in a string is really just as simple as calling the Replace function on a string. Please note that when you call Replace on a string, it does not modify the original string, it creates and returns a new string. I only bring this up because you set two different integer variables to pt.Length, and at no point is the string pt actually modified. Also, I would imagine you are getting the "Index was outside of array bounds" from the nested for loop. You have the loop set up in a way that m will decrement forever. However, once m equals zero, you will be trying to access an index of -1 from buffer2, which is a no no. If you want to delete the spaces while retaining an original copy of the string you could simplify your code to this:
string pt = "My name is Code";
string newpt = pt.Replace(" ", string.empty);
pt is a string with spaces, newpt is a new string with spaces removed. However, if you want to replace multiple consecutive spaces with a single space, I would recommend following the answer Panagiotis Kanavos gave.
I followed the advice of #maccettura and I did it like this and it worked as I wished :)
string orignalString = "";
orignalString = pt;
char[] buffer = pt.ToCharArray();
orignalString = new string(buffer);
return orignalString.Replace(" ", string.Empty);
// Here I got the string without spaces , now I have the same string with and without spaces
I'm also not allowed to use lists.
My initial thought process for this was to take the initial string then to turn that into a char array. Then after copy everything that is not a space to a second char array. Then convert that char array back to a string.
So quickly it would look something like this;
char[] firstArray;
char[] secondArray;
string someString;
for (int i = 0; i < someString.Length; i++)
{
firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];
for (int j = 0; j < firstArray.Length; j++)
{
if (firstArray[j] != ' ')
{
secondArray[j] = firstArray[j];
}
}
someString = secondArray.ToString();
}
But when I initialise the second char array it would contain an extra char with no value if there was a space in it initially, since it was initialised to the same size as the first char array. Would I have to do a similar loop before just to count the amount of non-spaces then initialise secondArray based off that or is there a much simpler way than all of this that I am missing? (Without the use of .trim, .replace(or anything like them) or lists)
Any help would be appreciated.
A String already implements IEnumerable<char>, so no need to turn it into an array to begin with. You can enumerate it directly and remove whitespace chars. E.g:
string x = " Hello, world";
string trimmed = new String(x.Where(c => !Char.IsWhiteSpace(c)).ToArray());
Your code re-creates the firstArray array every time. And I'm not sure what the inner loop is for. Your code fixed:
char[] firstArray;
char[] secondArray;
string someString = "Blah blah blah";
firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];
int newLength = 0;
for (int i = 0; i < firstArray.Length; i++) {
if (firstArray[i] != ' ') {
secondArray[newLength++] = firstArray[i];
}
}
someString = new string(secondArray, 0, newLength);
Another way using StringBuilder:
string someString = "Blah blah blah";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(char c in someString) {
if (!Char.IsWhiteSpace(c)) {
sb.Append(c);
}
}
someString = sb.ToString();
I have a task to read n given numbers in a single line, separated by a space ( ) from the console.
I know how to do it when I read every number on a separate line (Console.ReadLine()) but I need help with how to do it when the numbers are on the same line.
You can use String.Split. You can provide the character(s) that you want to use to split the string into multiple. If you provide none all white-spaces are assumed as split-characters(so new-line, tab etc):
string[] tokens = line.Split(); // all spaces, tab- and newline characters are used
or, if you want to use only spaces as delimiter:
string[] tokens = line.Split(' ');
If you want to parse them to int you can use Array.ConvertAll():
int[] numbers = Array.ConvertAll(tokens, int.Parse); // fails if the format is invalid
If you want to check if the format is valid use int.TryParse.
You can split the line using String.Split():
var line = Console.ReadLine();
var numbers = line.Split(' ');
foreach(var number in numbers)
{
int num;
if (Int32.TryParse(number, out num))
{
// num is your number as integer
}
}
You can use Linq to read the line then split and finally convert each item to integers:
int[] numbers = Console
.ReadLine()
.Split(new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray();
You simply need to split the data entered.
string numbersLine = console.ReadLine();
string[] numbers = numbersLine.Split(new char[] { ' '});
// Convert to int or whatever and use
This will help you to remove extra blank spaces present at the end or beginning of the input string.
string daat1String = Console.ReadLine();
daat1String = daat1String.TrimEnd().TrimStart();
string[] data1 = daat1String.Split(null);
int[] data1Int = Array.ConvertAll(data1, int.Parse);
you can do
int[] Numbers = Array.ConvertAll(Console.ReadLine().Split(' '),(item) => Convert.ToInt32(item));
the above line helps us get individual integers in a Line , separated by a
Single space.Two Or More spaces between numbers will result in error.
int[] Numbers = Array.ConvertAll(Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), (item) => Convert.ToInt32(item));
this variation will Fix the error and work well even when two or more spaces between numbers in a Line
you can use this function, it's very helpful
static List<string> inputs = new List<string>();
static int input_pointer = 0;
public static string cin(char sep = ' ')
{
if (input_pointer >= inputs.Count)
{
string line = Console.ReadLine();
inputs = line.Split(sep).OfType<string>().ToList();
input_pointer = 0;
}
string v = inputs[input_pointer];
input_pointer++;
return v;
}
Example:
for(var i =0; i<n ; i++)
for (var j = 0; j<n; j++)
{
M[i,j] = Convert.ToInt16(cin());
}
I am writing a program which should display the items from an array in a foreach loop.
I wanted to change the elements of the array by adding a string "sad" to each element, but when run the program the array stays the same.
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string[] stringArray = {"hey", "Tom"};
for (int i = 0; i < stringArray.Length; i++ )
{
stringArray[i] += " dad";
Console.WriteLine(stringArray[i]);
}
Array.Resize(ref stringArray, stringArray.Length + 1);
// Add bob to the last element of the array
stringArray[stringArray.Length - 1] =" bob";
foreach (string s in stringArray)
{
string b = s + "sad";
Console.WriteLine(s);
//Console.WriteLine(stringArray);
}
}
}
}
foreach (string s in stringArray)
{
string b = s + "sad";
// ...
}
Here you are creating a new string, completely unrelated to the string in the string-array. You haven't changed the old string (you can't; strings are immutable). You then simply drop this new longer string on the floor - you aren't updating the array etc.
Try instead something like:
for(int i = 0 ; i < stringArray.Length ; i++)
{
stringArray[i] = stringArray[i] + "sad";
}
This replaces every item in the array with a new string. Note that you can't update a list/collection/array etc while iterating with foreach - that can break the iterator. Hence the for loop instead.
Apart from what Chris said, you could simply use LINQ to achieve what you want:
string[] newStringArray = stringArray
.Select(s => s + "sad")
.ToArray();
string b = s + "sad";
Console.WriteLine(s);
//Console.WriteLine(stringArray);
At no point in your code do you alter values in the array. You create a new string from each value in the array, concatenated with the string "sad".
Solution
You can not alter a for-each variable. You'll get a message like:
Cannot assign to 's' because it is a 'foreach iteration variable'.
Instead, settle for a simple for loop.
for(int x = 0; x < stringArray.length; x++)
{
stringArray[x] = stringArray[x] + "sad";
}
Look at this part of the code:
string b = s + "sad";
Console.WriteLine(s);
You are concatenating the string in s with the string "sad", and storing in the variable b. Then you display the content of the variable s. If you would display the content of the variable b isntead, there would be a sad at the end of each string.
I am basically looking for a way to check if a certain string contains any of a certain list of chars, and if contains one of these to split the string and then insert the same char infront/after it. This is because these certain chars are breaking my search when they are input due to SQL not handling them well.
This is how far I have actually got so far:
string[] errorChars = new string[]
{
"!",
"}",
"{",
"'",
};
for (int i = 0; i < errorChars.Count(); i++)
{
if(fTextSearch.Contains(errorChars[i]))
{
}
}
The problem with several answers (in their current rendition) is that they are dropping your split character. If you need to keep your split character, try this:
StringBuilder sb = new StringBuilder();
string[] splitString = fTextSearch.Split(errorChars, StringSplitOptions.None);
int numNewCharactersAdded = 0;
foreach( string itm in splitString)
{
sb.Append(itm); //append string
if (fTextSearch.Length > (sb.Length - numNewCharactersAdded))
{
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded]); //append splitting character
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded - 1]); //append it again
numNewCharactersAdded ++;
}
}
fTextSearch = sb.ToString();
Here's an IDEOne example
I think what you are really wanting is a replace function.
for (int i = 0; i < errorChars.Count(); i++)
{
if(fTextSearch.Contains(errorChars[i]))
{
fTextSearch.Replace(errorChars[i],errorChars[i] + errorChars[i]);
}
}
although doubling up the character is probably not the answer. You need the escape char which is \ so the replace string would be
ftextSearch.Replace(errorChars[i],"\"+errorChars[i]);