Replace Characters in a string except values inside double quote - c#-4.0

I want to replace an array of characters with empty space except values inside double quote in a string.
Example
"India & China" relationship & future development
In the above example, I need to replace & but thats not inside any of the double quotes(""). The expected result should be
Result
"India & China" relationship future development
Other Examples of String
relationship & future development "India & China" // Output: relationship future development "India & China"
"relationship & future development India & China // Output: reflect the same input string as result string when the double quote is unclosed.
I have so far done the below logic to replace the characters in a string.
Code
string invalidchars = "()*&;<>";
Regex rx = new Regex("[" + invalidchars + "]", RegexOptions.CultureInvariant);
string srctxtaftrep = rx.Replace(InvalidTxt, " ");
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
srctxtaftrep = regex.Replace(srctxtaftrep, #" ");
InvalidTxt = srctxtaftrep;

Here's a non-regex approach using a StringBuilder which should work:
string input = "\"India & China\" relationship & future development";
HashSet<char> invalidchars = new HashSet<char>("()*&;<>");
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
foreach(char c in input)
{
if(c == '"') inQuotes = !inQuotes;
if ((inQuotes && c != '"') || !invalidchars.Contains(c))
sb.Append(c);
}
string output = sb.ToString();

Related

How to parse a string for numbers and words (strings)? IN JAVA

I have a list of strings that contain names and a series of numbers, ex: "John James Hollywood 1 2 3".
I want to parse out the names using a loop so that I can scan each part of the text and store it in a new string variable. Then I tried to use a conditional to put any numbers in a different variable. I will calculate the average of the numbers and then print the name and the average of the numbers, so the output looks like this:
John James Hollywood: 2
I don't know whether to use the input string stream or what my first steps are.
public static String parseNameNumbers(String text)
{
Scanner scnr = new Scanner(text);
Scanner inSS = null;
int numSum = 0;
int countNum = 0;
String newText = new String();
String sep = "";
while(scnr.hasNext()) {
if(scnr.hasNextInt()) {
numSum = numSum + scnr.nextInt();
countNum++;
}
else {
newText = newText + sep + scnr.next();
sep = " ";
}
}
return newText + ": " + (numSum/countNum);
}

Remove some text from a string after some constant value(string)

Input: String str="Fund testing testing";
Output: str="Fund";
After fund whatever the text is there need to remove that text.
Please suggest some solution.
The easiest way to solve this is a .Substring() method, as you can provide it the start index of your original string and length of the string you need:
var length = "Fund".Length;
var str = "Fund testing testing";
Console.WriteLine(str.Substring(0, length)); //returns "Fund"
var str1 = "testFund testing testing";
Console.WriteLine(str1.Substring(4, length)); //returns "Fund"
var str2 = "testFund testing testing";
Console.WriteLine(str2.Substring(str2.IndexOf("Fund"), length)); //returns "Fund"
You can also use regular expression like this:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = #"Fund testing testing";
string strReplace = #"$1";
return myRegex.Replace(strTargetString, strReplace);
As mentioned in comments below, replace can lack performance and is kind of overkill, so regex Match can be better. Here is how it looks like:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = "\n\n" + #" Fund testing testing";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var fund = myMatch.Groups[1].Value;
Console.WriteLine(fund);
}
}
Note that Groups first element is your entire match

How to split a string into multiple strings if spaces are detected (GM:Studio)

I made a console program, but the problem is that it doesn't allow parameters to be inserted. So I'm wondering how would I split a single string into multiple strings to achieve what I need. E.g.: text="msg Hello" would be split into textA="msg" and textB="Hello"
This is the main console code so far (just to show the idea):
if (keyboard_check_pressed(vk_enter)) {
text_console_c = asset_get_index("scr_local_"+string(keyboard_string));
if (text_console_c > -1) {
text_console+= "> "+keyboard_string+"#";
script_execute(text_console_c);
text_console_c = -1;
}
else if (keyboard_string = "") {
text_console+= ">#";
}
else {
text_console+= "> Unknown command: "+keyboard_string+"#";
};
keyboard_string = "";
}
I cant recommend spliting string with iteration by char, because when u try split very very very long string, then time to split is very long and can freeze thread for a short/long time. Game maker is single threaded for now.
This code is much faster.
string_split
var str = argument[0] //string to split
var delimiter = argument[1] // delimiter
var letDelimiter = false // append delimiter to each part
if(argument_count == 3)
letDelimiter = argument[2]
var list = ds_list_create()
var d_at = string_pos(delimiter, str)
while(d_at > 0) {
var part = string_delete(str, d_at , string_length(str))
if(letDelimiter)
part = part + delimiter
str = string_delete(str, 1, d_at)
d_at = string_pos(delimiter, str)
ds_list_add(list, part)
if(d_at == 0 && str != "")//last string without delimiter, need to add too
ds_list_add(list, str)
}
return list;
Dont forget ds_list_destroy after you iterate all strings
for example:
var splited = string_split("first part|second part", '|')
for(splited) {
//do something with each string
}
ds_list_destroy(splited)
Something like this may help, haven't tested it out but if you can follow what is going on its a good place to start.
Text = "msg Hello"
counter = 0
stringIndex = 0
for (i = 0; i < string_length(text); i++)
{
if string_char_at(text,i) == " "
{
counter++
stringIndex = 0
} else {
string_insert(string_char_at(text,i),allStrings(counter),stringIndex)
stringIndex++
}
}
allStrings should be an array containing each of the separate strings. Whenever a " " is seen the next index of allStrings starts having it's characters filled in. stringIndex is used to add the progressive characters.

String search logic - not language specific

I'm having to check data entry on an address field. The client does not want users to use terms like Rd. or Rd for road, ave or ave. for avenue etc. I have no problem with most of the terms. Where I have issues is with 'Ave' lets say. If I look for ' AVE ', that's fine but it will not pick up on ' AVE' at the end of the string and if I look for ' AVE' it will get a false positive on ' Avenue' since it will find ' Ave' within that string. Anyone have an idea of how I can go about this?
Thank you for any help.
Norst
Although the Q: is not language specific, here is how I'm going about this in JS:
//function to check address for rd rd. ave ave. st st. etc
function checkaddy() {
//array of items to look for
var watchfor = Array();
watchfor[0] = " RD";
watchfor[1] = " RD.";
watchfor[2] = " AVE ";
watchfor[3] = " AVE.";
watchfor[4] = " ST ";
watchfor[5] = " ST.";
watchfor[6] = " BLVD.";
watchfor[7] = " CRT ";
watchfor[8] = " CRT.";
watchfor[9] = " CRES ";
watchfor[10] = " CRES.";
watchfor[11] = " E ";
watchfor[12] = " E.";
watchfor[13] = " W ";
watchfor[14] = " W.";
watchfor[15] = " N ";
watchfor[16] = " N.";
watchfor[17] = " S ";
watchfor[18] = " S.";
watchfor[19] = " PKWY ";
watchfor[20] = " PKWY.";
watchfor[21] = " DR ";
watchfor[22] = " DR.";
//get what the user has in the address box
var addcheck = $("#address").val();
//upper case the address to check
addcheck = addcheck.toUpperCase();
//check to see if any of these terms are in our address
watchfor.forEach(function(i) {
if (addcheck.search(watchfor[i]) > 0 ) {
alert("Found One!");
}
});
}
Perhaps you need to look for word boundary character \b. Here are some Ruby examples:
irb(main):002:0> " Avenue" =~ / AVE\b/i
=> nil
irb(main):003:0> " Ave" =~ / AVE\b/i
=> 0
irb(main):005:0> " Ave" =~ /\bAVE\b/i
=> 1
irb(main):006:0> " Ave" =~ /\bAVE\b/i
Notice how " Avenue" doesn't match while " AVE" does match. Also notice how the '\b' behaves and we get 0 and 1 respectively.
There are other characters classes as well in regular expressions. So all you need to do is formulate correct REs for your problem set.
I hope that helps.
Why would your client insist on spelling out names? The United States Postal Service actually encourages abbreviations. Not only that, they prefer addresses to be in all uppercase letters and no more than 5 lines. Such specifications are what their automated sorters were built for. But I digress.
To actually answer your question, you may consider the following code. There was a mistake in your forEach declaration. You were using i as an index, but, in fact, the forEach function uses the whole entry of the array. I modified it below. Also, because we're using a string expression in the constructor for the RegExp, the \ in the \b has to be escaped, so we add two \'s inside the string. Because we using the \b construct for word boundaries, we don't need to add extra periods into the test array. I hope you find this helpful.
//array of items to look for
var watchfor = ['RD','AVE','ST','BLVD','CRT','CRES','E','W','N','S','PKWY','DR'];
//function to check address for rd rd. ave ave. st st. etc
function checkaddy(address) {
//check to see if any of these terms are in our address
watchfor.forEach(function(entry) {
var patt1 = RegExp('.*\\b' + entry + '\\b.*','gim');
if (patt1.test(address)) {
document.write("Found " + entry);
}
});
}

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);
Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.
Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.
Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

Resources