How to bring back removed spaces - c#

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

Related

C# read string from back to end

I have a string. For example :
string a = "abcdef098403248";
My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:
string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
As you see there, i store the numbers from left to right, but i want to read them from right to left.
Another example of what i want:
string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
Or:
string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
Regardless, thanks.
Stack<char> is your friend:
var stack = new Stack<char>();
foreach (var c in a.Reverse())
{
if (!char.IsDigit(c))
break;
stack.Push(c);
}
return new string(stack.ToArray());
Reverse the string using the function below.
Grab the number the wrong way around - spin it back.
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
Taken from : Best way to reverse a string
string str = "3333333a224444";
var reversedStr = str.Reverse();
string result= new String(reversedStr.TakeWhile(Char.IsDigit).ToArray());
I came up with this. Not as elegant as others. It adds the numbers to the string until it encounters a letter again then stops.
string a = "aBcdef3213BBBBB0913456";
var charList = a.ToCharArray();
string newString = string.Empty;
foreach (var letter in charList.Reverse())
{
var number = 0;
if (Int32.TryParse(letter.ToString(), out number))
{
newString = string.Format("{0}{1}", letter, newString);
}
else
{
break;
}
}
string a = "saffsa1ad12314";
string finalString = string.Empty;
char[] chars = a.ToCharArray();
for (int i = chars.Length -1; i >= 0; i--)
{
if (char.IsDigit(chars[i]))
{
finalString += chars[i];
}
else
{
break; //so you dont get a number after a letter
//could put your mbox here
}
}
//Now you just have to reverse the string
char[] revMe = finalString.ToCharArray();
Array.Reverse(revMe);
finalString = string.Empty;
foreach (char x in revMe)
{
finalString += x;
}
Console.WriteLine(finalString);
//outputs: 12314
This question feels awfully homeworky - but here is a very verbose way
of solving your problem. Alternatively you can read up on regex in c#.

C# replace different characters in a string

Everyone knows how to replace a character in a string with:
string text = "Hello World!";
text = text.Replace("H","J");
but what I need is to replace multiple characters in a string
something like:
string text = textBox1.Text;
text = text.Replace("a","b")
text = text.Replace("b","a")
now the result is aa , but if the user types ab I want the result to be ba
There's multiple ways to do this.
Using a loop
char[] temp = input.ToCharArray();
for (int index = 0; index < temp.Length; index++)
switch (temp[index])
{
case 'a':
temp[index] = 'b';
break;
case 'b':
temp[index] = 'a';
break;
}
string output = new string(temp);
This will simply copy the string to a character array, fix each character by itself, then convert the array back into a string. No risk of getting any of the characters confused with any of the others.
Using a regular expression
You can exploit this overload of Regex.Replace:
public static string Replace(
string input,
string pattern,
MatchEvaluator evaluator
)
This takes a delegate that will be called for each match, and return the final result. The delegate is responsible for returning what each match should be replaced with.
string output = Regex.Replace(input, ".", ma =>
{
if (ma.Value == "a")
return "b";
if (ma.Value == "b")
return "a";
return ma.Value;
});
For your particular requirement I would suggest you to use like the following:
string input = "abcba";
string outPut=String.Join("",input.ToCharArray()
.Select(x=> x=='a'? x='b':
(x=='b'?x='a':x))
.ToArray());
The output string will be bacab for this particular input
Do not call String.Replace multiple times for the same string! It creates a new string every time (also it has to cycle through the whole string every time) causing memory pressure and processor time waste if used a lot.
What you could do:
Create a new char array with the same length as the input string. Iterate over all chars of the input strings. For every char, check whether it should be replaced. If it should be replaced, write the replacement into the char array you created earlier, otherwise write the original char into that array. Then create a new string using that char array.
string inputString = "aabbccdd";
char[] chars = new char[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
if (inputString[i] == 'a')
{
chars[i] = 'b';
}
else if (inputString[i] == 'b')
{
chars[i] = 'a';
}
else
{
chars[i] = inputString[i];
}
}
string outputString = new string(chars);
Consider using a switch when intending to replace a lot of different characters.
Use should use StringBuilder when you are concatenating many strings in a loop like this, so I suggest the following solution:
StringBuilder sb = new StringBuilder(text.Length);
foreach(char c in text)
{
sb.Append(c == 'a' ? 'b' : 'a');
}
var result = sb.ToString();

How would you go about removing whitespace from a string without the use of methods such as .trim or .replace?

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();

How to compare string with another string using c#

I have a situation where i don't want to compare total string length to other string .
Example:
string MainString = "Deanna Ecker";
string SearchString = "Ecker Designs";
int value = MainString.IndexOf(SearchString);
here it is searching with whole string. but i need to find any word in MainString. not with whole string..
Let me know how is this possible.
If case-sensitivity is not an issue, you could split both strings by the space, then intersect the two lists to see if there are any matches:
var foundWords = MainString.Split(' ').Intersect(SearchString.Split(' '));
Or if you only want to know if a word was found:
var isMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();
you can convert your string to a char array then search each character via looping from all characters
such that
public bool MatchString(string first,string second)
{
char[] ch1=first.ToCharArray();
char[] ch2=second.ToCharArray();
bool match=false;
for(int i=0 ; i<ch1.length ; i++)
{
for(int j=0 ; j<ch2.length ; j++)
{
if(ch2[j]==ch[i])
{
match=true;
break;
}
}
}
return match;
}
Try: var wordMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();

Finding a char from an array, spliting at that point and then inserting another char after

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]);

Categories