Eliminating characters from string - c#

I am reading from a file, and some of the data is comming in like this
"\"ZIP\""
so when i try to assign it its causing errors, i want to get rid off the extra \", so if I assign it to as string like
string s = data[1].ToString();
what s is "\"ZIP\""
i just want it to be "ZIP", i tried:
string s = data[1].ToString().replace("\\\"","");
but no luck. Any help would be much appreciated.

just try:
var result = "\"ZIP\"".Replace("\"", "");
Or:
var result = "\"ZIP\"".Trim('"');

String.Trim could be used with an array of char to remove from start and end of a string
char[] charsToTrim = { '"', '\\'};
string s = data[1].ToString().Trim(charsToTrim);

Remove the escape characters in the string by split and create new string. You can include as many characters in escape sequence array as you want.
StringBuilder sb = new StringBuilder();
string[] parts = inputString.Split(new char[] {'"'};
StringSplitOptions.RemoveEmptyEntries);
int size = parts.Length;
for (int i = 0; i < size; i++)
sb.AppendFormat("{0} ", parts[i]);=
string strWithoutEscape = sb.ToString();

Try:
data[1].toString().replace("\\\"", "");
Notice that the function is case-sensitive, so using ToString would fail.

Related

How to bring back removed spaces

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

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

Splitting a string in C#, why is this not working?

I have the following string:
string myString = " The objective for test.\vVision\v* Deliver a test
goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities
strategy\vApproach\v*An acceleration "
and I am trying to split on "\v"
I tried this but it doesn't seem to work:
char[] delimiters = new char[] { '\v' };
string[] split = myString.Split(delimiters);
for (int i = 0; i < split.Length; i++) {
}
split.Length shows up as 1. Any suggestions?
"\v" is two characters, not one, in your original string (which is not counting the \ as an escape character as a literal C# string does).
You need to be splitting on literal "\v" which means you need to specify the overload of Split that takes a string:
string[] split = narrative.Split(new string[] {"\\v"}, StringSplitOptions.None);
Note how I had to escape the "\" character with "\\"
Your '\v' is a single control character, not two characters.
I think your question itself is slightly misleading...
Your example string, if entered into C# will actually work like you expected, because a \v in a verbatum C# string will be escaped to a special character:
string test = " The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration ";
char[] delimiters = new char[] { '\v' };
Console.WriteLine(test.Split(delimiters).Length); // Prints 8
However, I think your actual string really does have backslash-v in it rather than escaped \v:
string test = " The objective for test.\\vVision\\v* Deliver a test goals\\v** Comprehensive\\v** Control\\v* Alignment with cross-Equities strategy\\vApproach\\v*An acceleration ";
char[] delimiters = new char[] { '\v' };
Console.WriteLine(test.Split(delimiters).Length); // Prints 1, like you say you see.
So you can fix it as described above by using an array of strings to split the string:
string test = " The objective for test.\\vVision\\v* Deliver a test goals\\v** Comprehensive\\v** Control\\v* Alignment with cross-Equities strategy\\vApproach\\v*An acceleration ";
string[] delimiters = new [] { "\\v" };
Console.WriteLine(test.Split(delimiters, StringSplitOptions.None).Length); // Prints 8
Use something like this
string[] separators = {#"\v"};
string value = #"The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
If you don't need the resulting array for later use, you can combine the split and loop into one call.
foreach (string s in myString.Split(new[] { "\v" }, StringSplitOptions.RemoveEmptyEntries))
{
//s is the string you can now use in your loop
}
Use Like this,
string myString = " The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration";
string[] delimiters = new string[] { "\v" };
string[] split = myString.Split(delimiters, StringSplitOptions.None);
for (int i = 1; i < split.Length; i++)
{
}
Try running it like this.
public static string FirstName(string fullName)
{
if (fullName == null)
return null;
var split = fullName.Split(',');
return split.Length > 0 ? split[0] : string.Empty;
}

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

Edit array elements

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

Categories