select alternate alphabet from string of word in asp.net - c#

I want to generate alternate alphabets from generated word string. E.g. Word is SPACEORION then alphabet should be like this SPCO. Because I need to generate client code as per their name. What would be the suitable solution?

ok, from I understand, this might be what you want but the result of SPACEORION would be SAER and not SACO, so I hope I understood you correctly
string name = "SPACEORION ";
var shortName = "";
while (shortName.Length < 4)
{
foreach (char ch in name.ToCharArray())
{
if (name.IndexOf(ch) % 2 == 0)
{
shortName += ch.ToString();
}
}
}

Related

Converting Arabic Words to Unicode format in C#

I am designing an API where the API user needs Arabic text to be returned in Unicode format, to do so I tried the following:
public static class StringExtensions
{
public static string ToUnicodeString(this string str)
{
StringBuilder sb = new StringBuilder();
foreach (var c in str)
{
sb.Append("\\u" + ((int)c).ToString("X4"));
}
return sb.ToString();
}
}
The issue with the above code that it returns the unicode of letters regardless of its position in word.
Example: let us assume we have the following word:
"سمير" which consists of:
'س' which is written like 'سـ' because it is the first letter in word.
'م' which is written like 'ـمـ' because it is in the middle of word.
'ي' which is written like 'ـيـ' because it is in the middle of word.
'ر' which is written like 'ـر' because it is last letter of word.
The above code returns unicode of { 'س', 'م' , 'ي' , 'ر'} which is:
\u0633\u0645\u064A\u0631
instead of { 'سـ' , 'ـمـ' , 'ـيـ' , 'ـر'} which is
\uFEB3\uFEE4\uFEF4\uFEAE
Any ideas on how to update code to get correct Unicode?
Helpful link
The string is just a sequence of Unicode code points; it does not know the rules of Arabic. You're getting out exactly the data you put in; if you want different data out, then put different data in!
Try this:
Console.WriteLine("\u0633\u0645\u064A\u0631");
Console.WriteLine("\u0633\u0645\u064A\u0631".ToUnicodeString());
Console.WriteLine("\uFEB3\uFEE4\uFEF4\uFEAE");
Console.WriteLine("\uFEB3\uFEE4\uFEF4\uFEAE".ToUnicodeString());
As expected the output is
سمير
\u0633\u0645\u064A\u0631
ﺳﻤﻴﺮ
\uFEB3\uFEE4\uFEF4\uFEAE
Those two sequences of Unicode code points render the same in the browser, but they're different sequences. If you want to write out the second sequence, then don't pass in the first sequence.
Based on Eric's answer I knew how to solve my problem, I have created a solution on Github.
You will find a simple tool to run on Windows, and if you want to use the code in your projects then just copy paste UnicodesTable.cs and Unshaper.cs.
Basically you need a table of Unicodes for each Arabic letter then you can use something like the following extension method.
public static string GetUnShapedUnicode(this string original)
{
original = Regex.Unescape(original.Trim());
var words = original.Split(' ');
StringBuilder builder = new StringBuilder();
var unicodesTable = UnicodesTable.GetArabicGliphes();
foreach (var word in words)
{
string previous = null;
for (int i = 0; i < word.Length; i++)
{
string shapedUnicode = #"\u" + ((int)word[i]).ToString("X4");
if (!unicodesTable.ContainsKey(shapedUnicode))
{
builder.Append(shapedUnicode);
previous = null;
continue;
}
else
{
if (i == 0 || previous == null)
{
builder.Append(unicodesTable[shapedUnicode][1]);
}
else
{
if (i == word.Length - 1)
{
if (!string.IsNullOrEmpty(previous) && unicodesTable[previous][4] == "2")
{
builder.Append(unicodesTable[shapedUnicode][0]);
}
else
builder.Append(unicodesTable[shapedUnicode][3]);
}
else
{
bool previouChar = unicodesTable[previous][4] == "2";
if (previouChar)
builder.Append(unicodesTable[shapedUnicode][1]);
else
builder.Append(unicodesTable[shapedUnicode][2]);
}
}
}
previous = shapedUnicode;
}
if (words.ToList().IndexOf(word) != words.Length - 1)
builder.Append(#"\u" + ((int)' ').ToString("X4"));
}
return builder.ToString();
}

Remove certain letters from input string

I'm currently having a problem where when I search for a code I want to remove the any "."'s a user has inputted. The code I've done doesn't seem to be working and was wondering if someone could tell me why and what I need to do. Thanks.
foreach (var letters in id)
{
string letter = letters.ToString();
if (letter == ".")
{
id.Replace(letter, "");
}
}
String in .NET is an immutable type, therefore you can't change the value of an existing string variable, you need to replace it entirely with the value returned by Replace i.e.
id = id.Replace(letter, "");
FYI you don't have to check whether . is contained in the string, you can just call Replace(".", "") on the resultant string and it will remove any . present i.e.
id = id.Replace(".", "");
See example
String replace method
id = id.Replace(",", "");
Programmaticaly, maybe you can use that besides Replace() method
string m_tempStr = "This.is.a.test";
List<string> myList = new List<string>();
for (int i = 0; i < m_tempStr.Length; i++)
{
if (m_tempStr[i].ToString() != ".")
{
myList.Add(m_tempStr[i].ToString());
}
}
And than, you can get each member of list like following sample code
foreach (var item in myList)
{
Console.Write(item);
}

Validating header names for an SQL column list

I am currently trying to make a user friendly input for people to input SQL headers for a CSV that is created using a temporary table, however I am having issues with validating and changing the names to SQL friendly column headers.
An example input would be as follows:
Name, Ag-e, Gender, Birth Place, Rac+e
Please keep in mind that the input could be ANY word, these are simply an example.
My ideal final output would for the SQL column headers
name age gender birth_place race
however I am having issues checking for invalid characters (which I haven't actually got around to yet.) but my primary issue I am currently having is checking for spaces between words that SHOULD have a space and other spaces at the start of words.
My current output is coming out as(please note that the invalid characters are for testing later.):
Name Ag-e Gender Birth Place Rac+e
Please note that there are double spaces between every one apart from Birth Place which has a single space as it should.
The code I am currently using to achieve this (or not achieve as you can clearly see) is:
columnNamesList = new List<string>(columnNames.Split(splitChar));
columnNamesList[0] = columnNamesList[0].Trim();
columnNamesList[columnNamesList.Count - 1] = columnNamesList[columnNamesList.Count - 1].TrimEnd();
List<string> removalList = new List<string>();
foreach (string i in columnNamesList)
{
if (string.IsNullOrEmpty(i))
{
removalList.Add(i);
}
}
if (removalList.Count < 0)
{
foreach (string i in removalList)
{
columnNamesList.Remove(i);
}
}
for (int i = 0; i < columnNamesList.Count; i++)
{
string s = string.Empty;
string str = columnNamesList[i];
if (Regex.IsMatch(str, #"\w\s\w+", RegexOptions.IgnoreCase))
{
foreach (char c in str)
{
if (Char.IsLetterOrDigit(c) || c == ' ' || c == ',')
s += c;
s = s.Replace(' ', '_');
columnNamesList[i] = s;
}
}
}
string[] columnArray = columnNamesList.ToArray<string>();
columnNames = String.Join(" ", columnArray);
I thought you said that the input is like the first string, comma separated.
Does this not work? All you have to do is remove the unwanted characters (against a blacklist)
var input = "Name, Ag-e, Gender, Birth Place, Rac+e";
var splitInput = input.Split(',')
.Select(i =>
i.Trim()
.ToLower()
.Replace(' ','_'));
var output = string.Join(" ", splitInput.ToArray());

Get the different substrings from one main string

I have the following main string which contains link Name and link URL. The name and url is combined with #;. I want to get the string of each link (name and url i.e. My web#?http://www.google.com), see example below
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
and I want to get three different strings using any string function:
My web#?http://www.google.com
My Web2#?http://www.bing.se
Handbooks#?http://www.books.de
So this looks like you want to split on the space after a #;, instead of splitting at #; itself. C# provides arbitrary length lookbehinds, which makes that quite easy. In fact, you should probably do the replacement of #; with #? first:
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
teststring = Regex.Replace(teststring, #"#;", "#?");
string[] substrings = Regex.Split(teststring, #"(?<=#\?\S*)\s+");
That's it:
foreach(var s in substrings)
Console.WriteLine(s);
Output:
My web#?http://www.google.com
My Web2#?http://www.bing.se
Handbooks#?http://www.books.se/
If you are worried that your input might already contain other #? that you don't want to split on, you can of course do the splitting first (using #; in the pattern) and then loop over substrings and do the replacement call inside the loop.
If these are constant strings, you can just use String.Substring. This will require you to count letters, which is a nuisance, in order to provide the right parameters, but it will work.
string string1 = teststring.Substring(0, 26).Replace(";","?");
If they aren't, things get complicated. You could almost do a split with " " as the delimiter, except that your site name has a space. Do any of the substrings in your data have constant features, such as domain endings (i.e. first .com, then .de, etc.) or something like that?
If you have any control on the input format, you may want to change it to be easy to parse, for example by using another separator between items, other than space.
If this format can't be changed, why not just implement the split in code? It's not as short as using a RegEx, but it might be actually easier for a reader to understand since the logic is straight forward.
This will almost definitely will be faster and cheaper in terms of memory usage.
An example for code that solves this would be:
static void Main(string[] args)
{
var testString = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
foreach(var x in SplitAndFormatUrls(testString))
{
Console.WriteLine(x);
}
}
private static IEnumerable<string> SplitAndFormatUrls(string input)
{
var length = input.Length;
var last = 0;
var seenSeparator = false;
var previousChar = ' ';
for (var index = 0; index < length; index++)
{
var currentChar = input[index];
if ((currentChar == ' ' || index == length - 1) && seenSeparator)
{
var currentUrl = input.Substring(last, index - last);
yield return currentUrl.Replace("#;", "#?");
last = index + 1;
seenSeparator = false;
previousChar = ' ';
continue;
}
if (currentChar == ';' && previousChar == '#')
{
seenSeparator = true;
}
previousChar = currentChar;
}
}

Find and replace dynamic values via for loop

http://www.test.com/test.aspx?testinfo=&|&
I am trying to replace & with values from a table. I got name and age as two paramaters that I need to substitue and get url like this:
http://www.test.com/test.aspx?testinfo=name|age
If I have 3 string parameters to be replaced for a url:
http://www.test.com/test.aspx?testinfo=&|&
Viz name, age, address for the above url:
http://www.test.com/test.aspx?testinfo=name|age|address
string URL=string.Empty;
URL=http://www.test.com/test.aspx?testinfo=&|&;
//in this case fieldsCount is 2, ie. name and age
for(int i=0; i<fieldsCount.Length-1;i++)
{
URL.Replace("*","name");
}
How do I add "age" so that I get ? any inputs will be helpful.
http://www.test.com/test.aspx?testinfo=name|age
I think this is what you want,
List<string> keys = new List<string>() { "name", "age", "param3" };
string url = "http://www.test.com/test.aspx?testinfo=&|&;";
Regex reg = new Regex("&");
int count = url.Count(p => p == '&');
for (int i = 0; i < count; i++)
{
if (i >= keys.Count)
break;
url = reg.Replace(url, keys[i], 1);
}
I'm curious about two things.
Why are you using & as something to replace, when this has contextual
meaning within the query string as a delimiter between key/value
pairs?
Why does your string have just 2 fields (&|&), when sometimes
the value to replace it with has more than 2 keys?
If these things don't matter, it would make more sense to me to have a replacement string of something else... for instance http://www.test.com/test.aspx?testinfo=[testinfo]. Of course, you need to choose something that has 0 chance of showing up in your Url apart from where you expect it. You can then replace it with something like the following:
url = url.Replace("[testinfo]", string.Join("|", fieldsCount));
Note that this doesn't require your for-loop, and should result in your expected url.
See string.Join on msdn.
Concatenates all the elements of a string array, using the specified
separator between each element.
If I understood right, I think you need something like this:
private static string SubstituteAmpersands(string url, string[] substitutes)
{
StringBuilder result = new StringBuilder();
int substitutesIndex = 0;
foreach (char c in url)
{
if (c == '&' && substitutesIndex < substitutes.Length)
result.Append(substitutes[substitutesIndex++]);
else
result.Append(c);
}
return result.ToString();
}

Categories

Resources