How to make only chosen characters uppercase in C# [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want to make every other letter uppercase, how do I do that?
Code:
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i < a.Length; i++)
{
Console.Write(a.ToUpper()[i]+ ",");
}

Using Linq:
string a = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
var converted =
new string(a.Select((ch, i) => ((i % 2) == 0) ? ch : Char.ToUpper(ch)).ToArray());
Console.WriteLine(converted);

Increment your loop by 2.
Example:
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i<a.Length; i+=2)
Console.Write(a.ToUpper()[i]+ ",");
For every even alphabet start loop from 0 and for odd start from 1.

Linq answer is very good and has the advantage to be one liner, but a normal loop here is twice faster than the Linq solution
char[] a = "aábdeéðfghiíjklmnoóprstuúvxyýþæö".ToCharArray();
for (int i = 0; i < a.Length; i++)
{
if (i % 2 != 0)
{
a[i] = Char.ToUpper(a[i]);
}
}
string result = new string(a);

Using LINQ to go through each char in the string. If it is divisible by 2 then that means its every other letter. So make that upper case, if not divisible by 2 then leave it as it is. Rejoin all the chars together in an array then convert that back into a string.
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
var convertedString = new string(a
.Select((c, i) => (i + 1) % 2 == 0 ? Char.ToUpper(c) : c)
.ToArray());

String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i<a.Length; i++)
{
if (i % 2 == 0)
{
a = a.Substring(0, i) + a.Substring(i, 1).ToUpper() + a.Substring(i);
}
}
The % symbol is modulo, in this context if the index if divisible by 2 make the symbol upper case.
EDIT: as correctly pointed out, string are immutable, I've edited appropriately. This most likely isn't the most efficient way of doing this, I'd recommend using LINQ for a more efficient algorithm

You can use Linq.
string oldString = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
string alternatedString = string.Concat(
oldString.ToLower().Select((character, index) => index % 2 == 0 ? character : char.ToUpper(character)));
Output: aÁbDeÉðFgHiÍjKlMnOóPrStUúVxYýÞæÖ
Or
string oldString = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
StringBuilder alternatedString = new StringBuilder();
for(int index=0; index<oldString.Length; index++)
{
if(index % 2 == 0)
alternatedString.Append(oldString[index].ToString().ToLower());
else
alternatedString.Append(oldString[index].ToString().ToUpper());
}
Output: aÁbDeÉðFgHiÍjKlMnOóPrStUúVxYýÞæÖ

Related

How to remove count of specific byte in array C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I want to remove bytes from an array, I don't want to remove all bytes 0x6f I just want to remove two only of them. This is my code:
string msg = "gooooooal";
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
byte[] newArray = oldArray.Where(b => b != 0x6f).ToArray();
You can first find the position and then remove them
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
int howManyToRemove = 2; //How many items to remove
var positions = new List<int>();
int lastPos = -1;
for (int i = 0; i < howManyToRemove; i++)
{
var position = Array.IndexOf(oldArray, (byte)0x6f,lastPos+1);
if (position == -1)
{
break;
}
lastPos=position;
positions.Add(position);
}
byte[] newArray = oldArray.Where((val, idx) => !positions.Contains(idx)).ToArray();
If I understood your problem then if want to delete two occurrences of the letter o from your string because the 0x6f ASCII value is 111 which is the letter o.
and for that, you are making the solution very complex.
if can simply do like this.
string s = "gooooooal";
string output = removeChar(s, 'o'); //output will be gooool
static string removeChar(string s,
char ch)
{
int count = 2;
for (int i = 0; i < s.Length; i++)
{
// If ch is found
if (s[i] == ch && count > 0)
{
s = s.Substring(0, i) +
s.Substring(i + 1);
count--;
}
}
return s;
}

Generate random sequence of AlphaNumeric [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want a code to generate sequence of Alphanumeric character like LLNNLLNNLL where L is the Letter and N is the number. For example if the length is 5 the sequence will be LLNNL and if the length is 6 the sequence will be LLNNLL and if 7 it would be LLNNLLN.
string alphabets = "ABCDEFGHIJKLMNPQRSTUVWX";
int length = model.VALUE_INT;
string result = "";
for (int i = 0; i < length; i++)
{
int next = _random.Next(23);
result += alphabets.ElementAt(next);
result += _randomNum.Next(1, 9);
}
This is what I have tried but condition is not fulfilling
For each position (value of i) of your output string you need to check if you need a character or an integer.
Since the pattern repeats every 4 positions, you can achieve this using the modulo operator:
for (int i = 0; i < length; i++)
{
switch (i % 4)
{
case 0:
case 1:
int next = _random.Next(23);
result += alphabets.ElementAt(next);
break;
case 2:
case 3:
result += _randomNum.Next(1, 9);
break;
}
}
Or another possibility: Add blocks of LLNN and then truncate the result to the needed length...
for (int i = 0; i <= (length/4); i++)
{
result += alphabets.ElementAt(_random.Next(23));
result += alphabets.ElementAt(_random.Next(23));
result += _randomNum.Next(1, 9);
result += _randomNum.Next(1, 9);
}
result = result.Substring(0,length);
If you want to improve these lines, you can use a StringBuilder

Loop to write a cimma separated list of items [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to write a for loop that prints 49 through 1, with each value separated by a comma. So, it must not print a comma after the last value.
I have this so far and have no clue , after an hour of research, what else to do.
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + ",");
}
Just check where you are in your loop to know if you need to print the comma.
public static void Test()
{
for (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + (i != 1 ? "," : ""));
}
Console.ReadLine();
}
Check if you are at the last item, and don't write the comma in that case:
for (int i = 49; i >= 1; i--) {
Console.Write(i);
if (i > 1) {
Console.Write(",");
}
Console.WriteLine();
}
(There are alternatives that are a little more elegant, but this is closest to your original code. You can for example write the comma before the number and skip the first comma.)
You can use String.Join
List<string> numbers = new List<string>();
for (int i = 49; i >= 1; i--) {
numbers.Add(i.ToString());
}
string numberWithCommas = String.Join(",", numbers);
Console.WriteLine(numberWithCommas);
Or you can put in a if condition to check for the last element and conditionally print your comma.
The String.Join would be a neater way to do this operation. However as pointed out by #CommuSoft, if you are doing this operation for a large list of numbers, the memory used may be high in this operation.
Try this:
for (int i = 49; i >= 1; i--)
{
Console.Write("{0}{1}", i, i == 1 ? string.Empty : ",");
}
Your not keeping track of your value.
var content = String.Empty;
for(var i = 49; i >= 1; i--)
content += (i + ",");
Console.WriteLine(content);
Once you have a value, then you apply it. The problem your having is the scope never remains, it applies to a new line.
The value of i determines when to add the comma:
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i >= 1 ? i + "," : i);
}

Logic to generate an alphabetical sequence in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
The sequence should go like this.
A-Z,AA-AZ,BA-BZ,CA-CZ,.......,ZA-ZZ
After ZZ it should start from AAA.
Then AAA to ZZZ and then AAAA to ZZZZ and so on.
This sequence is pretty much like that of an Excel sheet.
Edit: Added my code
private void SequenceGenerator()
{
var numAlpha = new Regex("(?<Numeric>[0-9]*)(?<Alpha>[a-zA-Z]*)");
var match = numAlpha.Match(txtBNo.Text);
var alpha = match.Groups["Alpha"].Value;
var num = Convert.ToInt32(match.Groups["Numeric"].Value);
lastChar = alpha.Substring(alpha.Length - 1);
if (lastChar=="Z")
{
lastChar = "A";
txtBNo.Text = num.ToString() + "A" + alpha.Substring(0, alpha.Length - 1) + lastChar;
}
else
{
txtBNo.Text = num.ToString() + alpha.Substring(0, alpha.Length - 1) + Convert.ToChar(Convert.ToInt32(Convert.ToChar(lastChar)) + 1);
}
}
This is what I've done. But, I know that is a wrong logic.
Thanks.
As I've wrote in the comment, it's a base-conversion problem, where your output is in base-26, with symbols A-Z
static string NumToLetters(int num)
{
string str = string.Empty;
// We need to do at least a "round" of division
// to handle num == 0
do
{
// We have to "prepend" the new digit
str = (char)('A' + (num % 26)) + str;
num /= 26;
}
while (num != 0);
return str;
}
Lucky for you, I've done this once before. the problems I've encountered is that in the Excel sheet there is no 0, not even in double 'digit' 'numbers'. meaning you start with a (that's 1) and then from z (that's 26) you go straight to aa (27). This is why is't not a simple base conversion problem, and you need some extra code to handle this.
Testing the function suggested by xanatos results with the following:
NumToLetters(0) --> A
NumToLetters(25) --> Z
NumToLetters(26) --> BA
My solution has more code but it has been tested against Excel and is fully compatible, except it starts with 0 and not 1, meaning that a is 0, z is 25, aa is 26, zz 701, aaa is 702 and so on). you can change it to start from 1 if you want, it's fairly easy.
private static string mColumnLetters = "zabcdefghijklmnopqrstuvwxyz";
// Convert Column name to 0 based index
public static int ColumnIndexByName(string ColumnName)
{
string CurrentLetter;
int ColumnIndex, LetterValue, ColumnNameLength;
ColumnIndex = -1; // A is the first column, but for calculation it's number is 1 and not 0. however, Index is alsways zero-based.
ColumnNameLength = ColumnName.Length;
for (int i = 0; i < ColumnNameLength; i++)
{
CurrentLetter = ColumnName.Substring(i, 1).ToLower();
LetterValue = mColumnLetters.IndexOf(CurrentLetter);
ColumnIndex += LetterValue * (int)Math.Pow(26, (ColumnNameLength - (i + 1)));
}
return ColumnIndex;
}
// Convert 0 based index to Column name
public static string ColumnNameByIndex(int ColumnIndex)
{
int ModOf26, Subtract;
StringBuilder NumberInLetters = new StringBuilder();
ColumnIndex += 1; // A is the first column, but for calculation it's number is 1 and not 0. however, Index is alsways zero-based.
while (ColumnIndex > 0)
{
if (ColumnIndex <= 26)
{
ModOf26 = ColumnIndex;
NumberInLetters.Insert(0, mColumnLetters.Substring(ModOf26, 1));
ColumnIndex = 0;
}
else
{
ModOf26 = ColumnIndex % 26;
Subtract = (ModOf26 == 0) ? 26 : ModOf26;
ColumnIndex = (ColumnIndex - Subtract) / 26;
NumberInLetters.Insert(0, mColumnLetters.Substring(ModOf26, 1));
}
}
return NumberInLetters.ToString().ToUpper();
}
Try this method:
public static IEnumerable<string> GenerateItems()
{
var buffer = new[] { '#' };
var maxIdx = 0;
while(true)
{
var i = maxIdx;
while (true)
{
if (buffer[i] < 'Z')
{
buffer[i]++;
break;
}
if (i == 0)
{
buffer = Enumerable.Range(0, ++maxIdx + 1).Select(c => 'A').ToArray();
break;
}
buffer[i] = 'A';
i--;
}
yield return new string(buffer);
}
// ReSharper disable once FunctionNeverReturns
}
This is infinite generator of alphabetical sequence you need, you must restrict count of items like this:
var sequence = GenerateItems().Take(10000).ToArray();
Do not call it like this (it cause infinite loop):
foreach (var i in GenerateItems())
Console.WriteLine(i);

Linear Search Problem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.

Categories