C# Remove everything after specific word - c#

My input is:
something1#email.com.;;
something2#email.eu,./
something3#email.org..
something4#email.netcdsfsd
What I want is to get rid of all characters after my "domains"(stored in array).
So output should be:
something1#email.com
something2#email.eu
something3#email.org
something4#email.net
My code is:
string[] domains = richTextBox_domains.Text.Split(';');
char[] specialchars = ".!#$%^&*()-_=+[]{}\\|;:'\",.<>/?".ToCharArray();
for (int x = 0; x < domains.Length; x++)
{
for (int y = 0; y < specialchars.Length; y++)
{
string check = domains[x] + specialchars[y];
string aftertmp = "." + after.Substring(after.IndexOf('.') + 1);
if (aftertmp == check)
after = after.Replace(check, domains[x]);
}
}
It's working but not always and only for one character at the end.
I will be glad for help

use regex to check email id and than store it in different array
var regex1 = new Regex("(([-a-zA-Z0-9])|([-a-zA-Z0-9]{1,256}[#%._\+~#=][-a-zA-Z0-9])){1,10}\.[-a-zA-Z0-9]{1,10}\b",RegexOptions.IgnoreCase);
string[] domains = richTextBox_domains.Text.Split(';');
List<string> l = new List<string>();
for (int x = 0; x < domains.Length; x++)
{
var results = regex1.Matches(domains[x]);
foreach (Match match in results)
{
l.Add(match.Groups[1].Value);
MessageBox.Show(match.Groups[1].Value);
}
}
string[] s = l.ToArray();// new array
hope this helps

This works fine
string[] s = { ".com",".net",".edu",".eu" };
string[] domain = new string[]
{
"something1#email.com.;;",
"something2#email.eu,./",
"something3#email.org..",
"something4#email.netcdsfsd"
};
string result = "";
for (int m = 0; m < domain.Length; m++)
{
for (int i = 0; i < s.Length; i++)
{
if (domain[m].IndexOf(s[i]) != -1)
{
result = domain[m].Substring(0, domain[m].IndexOf(s[i])) + s[i];
MessageBox.Show(result);
}
}
}
}

Related

I am unable to use substring. How can I fix this?

I am trying to see weather the string is in alphabetical order or no and this error pops up
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at Rextester.Program.Main(String[] args)**
public static void Main(string[] args)
{
string str = "bat\ncat\ndog\n";
int c = 0;
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
c++;
}
}
String[] strArray = new String[c + 1]; //declare with size
int g = 0;
String h = "";
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
strArray[g] = h;
h = "";
g = g + 1;
}
else
{
h = h + str.Substring(i,i + 1);
}
}
String p = "True";
for (int i = 0; i < g; i++)
{
if (i < (g - 1))
{
String f = strArray[i];
String g2 = strArray[i + 1];
char d = f[0];
char s = g2[0];
int d1 = (int)d;
int s1 = (int)s;
if (d1 > s1)
{
p = "False";
}
}
}
Console.WriteLine(p);
}
}
Not sure about what you are doing in your second loop and why is it so complex. We can do the same like this. Hope this helps.
using System;
public class Program
{
public static void Main()
{
string str = "abcd";
str = str.Replace('\n',' ');
String p = "True";
for (int i = 1; i < str.Length; i++) {
// if element at index 'i' is less
// than the element at index 'i-1'
// then the string is not sorted
if (str[i] < str[i - 1]) {
p = "false";
}
}
Console.WriteLine(p);
}
}
Pay attention to the definition of substring
The substring starts at a specified character position and has a
specified length
Considering your first use of substring, here
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, i + 1).Equals("\n"))
{
c++;
}
}
What happens when we get to i=6 here? Substring tries to give you a new string that starts at position i = 6, and is length = 7 characters long. So it tries to give you 7 characters starting from str[6] to str[12]. Well, there is no str[12], so you get an exception.
Its clear that your intent is NOT to get a string that starts at position 6 and is 7 characters long. You want ONE character, so your loop should be this
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1).Equals("\n"))
{
c++;
}
}
But theres a much simpler way to get your words in alphabetical order using LINQ
string str = "bat\ncat\ndog\n";
//Removes the trailing \n so you don't have one entry that is only whitespace
str = str.Trim();
string[] strSplit = str.Split('\n').OrderBy(x => x[0]).ToArray();
Now all substrings are sorted alphabetically and you can do whatever you want with them

Error CS0030 Cannot convert type 'char' to 'string'

Hi so am trying to get this to read a config string for a game am trying to make a plugin what rewards people who are on the list this is my error.
i tried multiple things am getting a bunch of different errors and i just cant figure out how to do this.
Severity Code Description Project File Line Suppression State
Error CS0030 Cannot convert type 'char' to 'string' PerkPlugin C:\Users\f\Downloads\Smod2-master\Smod2-master\ExamplePlugin\PerkPlugin\PerkPlugin.cs 73 Active
using Smod2;
using Smod2.API;
using Smod2.Events;
using System;
namespace Smod.PerkPlugin
{
class RoundStartHandler : IEventRoundStart
{
private Plugin plugin;
private IConfigFile config;
public RoundStartHandler(Plugin plugin)
{
this.plugin = plugin;
}
public void OnRoundStart(Server server)
{
string[] ItemString = new string[15];
int[,,] ItemList = new int[15, 8, 16];
int[] maxitem = new int[15];
int[,] maxitemchance = new int[15, 8];
ItemString[(int)Classes.CLASSD] = plugin.GetConfigString("default_item_classd");
ItemString[(int)Classes.NTF_SCIENTIST] = plugin.GetConfigString("default_item_ntfscientist");
ItemString[(int)Classes.SCIENTIST] = plugin.GetConfigString("default_item_scientist");
ItemString[(int)Classes.CHAOS_INSUGENCY] = plugin.GetConfigString("default_item_ci");
ItemString[(int)Classes.NTF_LIEUTENANT] = plugin.GetConfigString("default_item_lieutenant");
ItemString[(int)Classes.NTF_COMMANDER] = plugin.GetConfigString("default_item_commander");
ItemString[(int)Classes.NTF_GUARD] = plugin.GetConfigString("default_item_guard");
ItemString[(int)Classes.TUTORIAL] = plugin.GetConfigString("default_item_tutorial");
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 8; j++)
{
for (int k = 0; k < 16; k++)
{
ItemList[i, j, k] = -1;
}
}
if (ItemString[i] != "-1" && ItemString[i] != null)
{
ItemString[i].Replace(" ", string.Empty);
string[] items = ItemString[i].Split(',');
for (maxitem[i] = 0; maxitem[i] < items.Length; maxitem[i]++)
{
string[] itemchance = items[maxitem[i]].Split(':');
for (maxitemchance[i, maxitem[i]] = 0; maxitemchance[i, maxitem[i]] < itemchance.Length; maxitemchance[i, maxitem[i]]++)
{
ItemList[i, maxitem[i], maxitemchance[i, maxitem[i]]] = System.Convert.ToInt32(itemchance[maxitemchance[i, maxitem[i]]]);
}
}
}
}
foreach (Player player in server.GetPlayers())
{
string playerIP = player.IpAddress;
string[] playerIPSplit = playerIP.Split(':');
playerIP = (playerIPSplit.Length >= 1 ? playerIPSplit[playerIPSplit.Length - 1] : playerIP).Trim();
string perks = plugin.GetConfigString("perk_ips");
foreach (string perkIP in plugin.GetConfigString("perk_ips"))
{
string[] perkIPSplit = perkIP.Split(':');
string endperkIP = (perkIPSplit.Length >= 1 ? perkIPSplit[perkIPSplit.Length - 1] : perkIP).Trim();
if (playerIP.Equals(endperkIP))
{
int classtype = (int)player.Class.ClassType;
if (classtype > -1 && classtype < 15)
{
foreach (Item item in player.GetInventory())
{
item.Remove();
}
for (int i = 0; i < maxitem[classtype]; i++)
{
Random rd = new Random();
int result = ItemList[classtype, i, rd.Next(0, maxitemchance[classtype, i])];
if (result != -1)
{
player.GiveItem((ItemType)result);
}
}
}
}
}
}
}
}
}
Thanks for any help :)
It looks like this line:
foreach (string perkIP in plugin.GetConfigString("perk_ips"))
has you iterating over a string, which results in a character. It appears that GetConfigString doesn't return a collection of strings, but only a single string.
Had a similar issue and the answer above gave me the idea to try this, so instead of
foreach (string perkIP in plugin.GetConfigString("perk_ips"))
you could try
foreach (var perkIP in plugin.GetConfigString("perk_ips"))
then in the portion where perkIp appears you just convert it from char to string
perkIp.ToString()
example like here:
string[] perkIPSplit = perkIP.Split(':');
string endperkIP = (perkIPSplit.Length >= 1 ? perkIPSplit[perkIPSplit.Length - 1] : perkIP).Trim();
to
string[] perkIPSplit = perkIP.ToString().Split(':');
string endperkIP = (perkIPSplit.Length >= 1 ? perkIPSplit[perkIPSplit.Length - 1] : perkIP.ToString()).Trim();

Substring word search produces too much output

I am trying to solve the coding problem below:
Given a dictionary of words
And user entered word to compare against
When comparing the given word against the dictionary
Then output all words in the dictionary that exist in the given word
E.g. StartBurst would output Star and Burst if those words were in the dictionary.
Below is my code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string w = Console.ReadLine();
string[] dictionary = new string[106];
{
string word = w;
string word2 = w;
string w1 = word;
string w2 = word2;
for (int n = 0; n < w.Length; n++)
{
w1 = word;
w2 = word;
for (int x = 0; x < word.Length; x++)
{
for (int i = 0; i < dictionary.Length; i++)
{
if (w1.Equals(dictionary[i]) && w1 != w2)
{
Console.WriteLine(w1);
Console.ReadLine();
}
if (w2.Equals(dictionary[i]) && w1 != w2)
{
Console.WriteLine(w2);
Console.ReadLine();
}
}
w1 = w1.Substring(1, w1.Length - 1);
w2 = word.Substring(0, word.Length - x);
}
word = word.Substring(1, word.Length - 1);
}
}
}
}
}
However, when I run this, it outputs far too much output. For example, if I enter "dontdo" the program outputs "dont do do do do do do". I believe this is due to the word = word.Substring(1, word.Length - 1); statement, but I am unsure how to rectify the situation. Can anyone help?
I created a small code snippet for you to find all the substrings that you need in your search.
void Main()
{
foreach(var w in createMatchables("real"))
{
Console.WriteLine(w);
}
}
// this creates all the searchable substrings from a given string
// all the strings are created from left to right
List<string> createMatchables(string str)
{
var matchList = new List<string>();
for (int i = str.Length; i != 0; i--)
{
var branchCount = str.Length / i;
for (int j = 0; j < branchCount; j++)
{
matchList.Add(str.Substring(i*j, i));
}
}
return matchList;
}

Create List of strings from the string inputted by the user c#

I have this method:
public List<string> AdvMultiKeySearch(string key)
{
string[] listKeys = key.Split(',');
string[] ORsplit;
List<string> joinedDashKeys = new List<string>();
List<string> joinedSearchKeys = new List<string>();
for (int i = 0; i < listKeys.Length; i++)
{
ORsplit = listKeys[i].Split('|');
joinedDashKeys.Add(string.Join(",", ORsplit));
}
for (int i = 0; i < joinedDashKeys.Count; i++)
{
string[] split = joinedDashKeys[i].Split(',');
for (int j = 0; j < split.Length; j++)
{
joinedSearchKeys.Add(string.Join(",", split[i]));
}
}
return joinedDashKeys;
}
I am trying to create a method that receives a string Keyword that is composed of the words,comas, and '|' character. For example, user enters
glu|sal,1368|1199
And method should produce/return List of strings: "glu,1368", "glu,1199", "sal,1368", "sal,1199"
It's been more than two hours and I still can't figure out how to correctly implement it. Can someone help please?
Given the input above this will show any number of combinations as long as there is one comma.
char[] splitter1 = new char[] { '|' };
char[] splitterComma = new char[] { ',' };
public List<string> AdvMultiKeySearch(string key)
{
List<string> strings = new List<string>();
string[] commaSplit = key.Split(splitterComma);
string[] leftSideSplit = commaSplit[0].Split(splitter1);
string[] rightSideSplit = commaSplit[1].Split(splitter1);
for (int l = 0; l < leftSideSplit.Length; l++)
{
for (int r = 0; r < rightSideSplit.Length; r++)
{
strings.Add(leftSideSplit[l] + "," + rightSideSplit[r]);
}
}
return strings;
}

How to split a deliminated string with encapsulation and escapes

I would like to split a string deliminated by a character such as ‘&’, but in the case where some values contain the deliminator I would like to escape with double quotes. What is an elegant approach to splitting while ignoring the deliminating characters that have been escaped while also accounting for escape character escapes?
For example split this string properly
var1=asdfasdf&var2=contain””quote&var3=”contain&delim”&var4=”contain””both&”
Into:
var1=asdfasdf
var2=contain"quote
var3=contain&delim
var4=contain"both&
Incidentally, I am thinking Regex...
My solution, with test:
void TestCharlesParse()
{
string s = #"var1=asdfasdf&var2=contain""""quote&var3=""contain&delim""&var4=""contain""""both&""";
string[] os = CharlesParse(s);
for (int i = 0; i < os.Length; i++)
System.Windows.Forms.MessageBox.Show(os[i]);
}
string[] CharlesParse(string inputString)
{
string[] escapedQuotes = { "\"\"" };
string[] sep1 = inputString.Split(escapedQuotes, StringSplitOptions.None);
bool quoted = false;
ArrayList sep2 = new ArrayList();
for (int i = 0; i < sep1.Length; i++)
{
string[] sep3 = ((string)sep1[i]).Split('"');
for (int j = 0; j < sep3.Length; j++)
{
if (!quoted)
{
string[] sep4 = sep3[j].Split('&');
for (int k = 0; k < sep4.Length; k++)
{
if (k == 0)
{
if (sep2.Count == 0)
{
sep2.Add(sep4[k]);
}
else
{
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep4[k];
}
}
else
{
sep2.Add(sep4[k]);
}
}
}
else
{
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + sep3[j];
}
if (j < (sep3.Length-1))
quoted = !quoted;
}
if (i < (sep1.Length - 1))
sep2[sep2.Count - 1] = ((string)sep2[sep2.Count - 1]) + "\"";
}
string[] ret = new string[sep2.Count];
for (int l = 0; l < sep2.Count; l++)
ret[l] = (string)sep2[l];
return ret;
}

Categories