Perform Select at odd positions in the string - c#

I have to Replace the characters of input string at odd positions by next character in alphabet.
For Example
Input- ABCD
output- BBDD
I wanted something like this
string input = Console.ReadLine();
char[] k = input.ToCharArray().Select((val,i) =>(i%2==0) && (char)((int)val + 1)).ToArray();
string output=new string(k)

You are almost there, need to do little more to achieve the target. You have to notice the Following things and make those changes:
The condition i%2==0 determines whether the character needs to be replaced or not, so you have to apply the conditional operator(?:) here.
For valid condition, you have to get the next character. For that you can try (char)((int)x + 1). this will first evaluate (int)x and gives the integer value of that particular character. then add 1 to it then get the corresponding character.
For false condition use the same character.
After these steps you will get a character array, you can use String.Join to make the output string from the character array
You can try something like this:
string input = "ABCD";
char[] k = input.Select((x, i) => i % 2 == 0 ? (char)((int)x + 1) : x).ToArray();
string output = String.Join("",k);
Working Example
Note the following things as well:
In this code we have not restricted characters, if your input contains Z the next value from the ASCII table will be assigned, that will be [.
If you want z to a and Z to A then you have to apply conditions for that.

string output = string.Concat(input.Select((c, i) => (char)(c + ++i % 2)));

Related

Remove all characters after the fourth space in a string

I want to remove all characters after the fourth space in a string.
Example:
Source: AAD BCCD QWD SDKE DJQWEK DJT
Result: AAD BCCD QWD SDKE
I tried to use 'String.indexof'. but, I couldn't.
Here is my code:
Result = source.Substring(source.IndexOf(string.Empty, source.IndexOf(string.Empty) + 3));
You could try this:
string result = string.Join(" ", source.Split(' ').Take(4));
This splits the original source string at each space character, takes the first 4 occurrences and concatenates them with a space character.
It will also work correctly in cases where there are less than 4 counts of spaces in the source string.
Maybe try this (if it's still actuall of course):
string Source = "AAD BCCD QWD SDKE DJQWEK DJT"
int space = GetNthIndex(Source, ' ', 4);
string result = sample.Substring(0, space);
You can make a loop with a counter and check each character. Pseudocode:
counter = 0;
foreach(character in string)
if(counter > 4)
exit;
else if(character == space)
counter++;
output character
else
output character

How to replace next Character of string with immediate character

I am trying to replace next character of string with immediate character.
For example,
given string is
"HOME"
required string should be
"EHOM",
Is it possible to do it without any replace function.
Seems like just moving the last character in front:
string s = "HOME";
s = s.Last() + s.Remove(s.Length - 1); // "EHOM"
approach "doing everything on foot":
make a char array as long as your string ... (no trailing null)
have a for loop with the index i go through the array
calculate the replacement position r = i - 1 + len(array) mod len(array)
fetch char from position r in the original string
put fetched char at position i of your array
end of loop
make a string from your array
Basic string functions:
string x = "Home";
string y = x.Substring(x.Length - 1, 1) + x.Substring(0, x.Length - 1);
Please note that you should declare a new string to respect immutability.

Delete the first char of a string and append to end of string

I need to get the first char of this string:
String s = "X-4711";
And put it after the number with an ';' , like: 4711;X.
I already tried it with:
String x = s.Split("-")[1] + ";" + s.Split("-")[0];
then I get it, but can I do it better or is this the only possible way?
var items = s.Split ("-");
string x = String.Format ("{0};{1}", items[1], items[0]);
At most this makes it a little more readable and a micro-optimisation of only having to split once.
EDIT :
As some of the comments have pointed out, if you are using C#6 you can make use of String Interpolation to format the string. It does the exact same thing, only looks a little better.
var items = s.Split ("-");
string x = $"{items[1]};{items[0])}";
Not sure what performance you are looking for small string operations, your code is well written and satisfy your needs.
One minor thing you might consider is removing additional split performed on input string.
var subs = s.Split ("-");
String.Format ("{0};{1}", subs [1], subs [0]);
If you are looking single liner (crazy programmer), this might help.
string.Join(";", s.Split('-').Reverse())
String.Substring: Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
string sub = input.Substring(0, 1);
string restStr = input.Substring(2, input.length-2);
// string restStr = input.Substring(2); Can also use this instead of above line
string madeStr = restStr + ";" + sub;
You call the Substring method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring method.

Regex. Camel case to underscore. Ignore first occurrence

For example:
thisIsMySample
should be:
this_Is_My_Sample
My code:
System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])", "_$0", System.Text.RegularExpressions.RegexOptions.Compiled);
It works fine, but if the input is changed to:
ThisIsMySample
the output will be:
_This_Is_My_Sample
How can first occurrence be ignored?
Non-Regex solution
string result = string.Concat(input.Select((x,i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
Seems to be quite fast too: Regex: 2569ms, C#: 1489ms
Stopwatch stp = new Stopwatch();
stp.Start();
for (int i = 0; i < 1000000; i++)
{
string input = "ThisIsMySample";
string result = System.Text.RegularExpressions.Regex.Replace(input, "(?<=.)([A-Z])", "_$0",
System.Text.RegularExpressions.RegexOptions.Compiled);
}
stp.Stop();
MessageBox.Show(stp.ElapsedMilliseconds.ToString());
// Result 2569ms
Stopwatch stp2 = new Stopwatch();
stp2.Start();
for (int i = 0; i < 1000000; i++)
{
string input = "ThisIsMySample";
string result = string.Concat(input.Select((x, j) => j > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
}
stp2.Stop();
MessageBox.Show(stp2.ElapsedMilliseconds.ToString());
// Result: 1489ms
You can use a lookbehind to ensure that each match is preceded by at least one character:
System.Text.RegularExpressions.Regex.Replace(input, "(?<=.)([A-Z])", "_$0",
System.Text.RegularExpressions.RegexOptions.Compiled);
lookaheads and lookbehinds allow you to make assertions about the text surrounding a match without including that text within the match.
Maybe like;
var str = Regex.Replace(input, "([A-Z])", "_$0", RegexOptions.Compiled);
if(str.StartsWith("_"))
str = str.SubString(1);
// (Preceded by a lowercase character or digit) (a capital) => The character prefixed with an underscore
var result = Regex.Replace(input, "(?<=[a-z0-9])[A-Z]", m => "_" + m.Value);
result = result.ToLowerInvariant();
This works for both PascalCase and camelCase.
It creates no leading or trailing underscores.
It leaves in tact any sequences of non-word characters and underscores in the string, because they would seem intentional, e.g. __HiThere_Guys becomes __hi_there_guys.
Digit suffixes are (intentionally) considered part of the word, e.g. NewVersion3 becomes new_version3.
Digit prefixes follow the original casing, e.g. 3VersionsHere becomes 3_versions_here, but 3rdVersion becomes 3rd_version.
Unfortunately, capitalized two-letter acronyms (e.g. in IDNumber, where ID would be considered a separate word), as suggested in Microsoft's Capitalization Conventions, are not supported, since they conflict with other cases. I recommend, in general, to resist this guideline, as it is a seemingly arbitrary exception to the convention of not capitalizing acronyms. Stick with IdNumber.
Elaborating on sa_ddam213's solution, mine extends this:
public static string GetConstStyleName(this string value)
{
return string.Concat(value.Select((x, i) =>
{
//want to avoid putting underscores between pairs of upper-cases or pairs of numbers, or adding redundant underscores if they already exist.
bool isPrevCharLower = (i == 0) ? false : char.IsLower(value[i - 1]);
bool isPrevCharNumber = (i == 0) ? false : char.IsNumber(value[i - 1]);
return (isPrevCharLower && (char.IsUpper(x) || char.IsNumber(x))) //lower-case followed by upper-case or number needs underscore
|| (isPrevCharNumber && (char.IsUpper(x))) //number followed by upper-case needs underscore
? "_" + x.ToString() : x.ToString();
})).ToUpperInvariant();
}
Use ".([A-Z])" for your regular expression, and then "_$1" for the replacement. So you use the captured string for the replacement and with the leading . you are sure you are not catching the first char of your string.
You need to modify your regex to not match the first char by defining you want to ignore the first char at all by
.([A-Z])
The above regex simply excludes every char that comes first and since it is not in the braces it would be in the matching group.
Now you need to match the second group like Bibhu noted:
System.Text.RegularExpressions.Regex.Replace(s, "(.)([A-Z])", "$1_$2", System.Text.RegularExpressions.RegexOptions.Compiled);

How to find the number of occurrences of a letter in only the first sentence of a string?

I want to find number of letter "a" in only first sentence. The code below finds "a" in all sentences, but I want in only first sentence.
static void Main(string[] args)
{
string text; int k = 0;
text = "bla bla bla. something second. maybe last sentence.";
foreach (char a in text)
{
char b = 'a';
if (b == a)
{
k += 1;
}
}
Console.WriteLine("number of a in first sentence is " + k);
Console.ReadKey();
}
This will split the string into an array seperated by '.', then counts the number of 'a' char's in the first element of the array (the first sentence).
var count = Text.Split(new[] { '.', '!', '?', })[0].Count(c => c == 'a');
This example assumes a sentence is separated by a ., ? or !. If you have a decimal number in your string (e.g. 123.456), that will count as a sentence break. Breaking up a string into accurate sentences is a fairly complex exercise.
This is perhaps more verbose than what you were looking for, but hopefully it'll breed understanding as you read through it.
public static void Main()
{
//Make an array of the possible sentence enders. Doing this pattern lets us easily update
// the code later if it becomes necessary, or allows us easily to move this to an input
// parameter
string[] SentenceEnders = new string[] {"$", #"\.", #"\?", #"\!" /* Add Any Others */};
string WhatToFind = "a"; //What are we looking for? Regular Expressions Will Work Too!!!
string SentenceToCheck = "This, but not to exclude any others, is a sample."; //First example
string MultipleSentencesToCheck = #"
Is this a sentence
that breaks up
among multiple lines?
Yes!
It also has
more than one
sentence.
"; //Second Example
//This will split the input on all the enders put together(by way of joining them in [] inside a regular
// expression.
string[] SplitSentences = Regex.Split(SentenceToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase);
//SplitSentences is an array, with sentences on each index. The first index is the first sentence
string FirstSentence = SplitSentences[0];
//Now, split that single sentence on our matching pattern for what we should be counting
string[] SubSplitSentence = Regex.Split(FirstSentence, WhatToFind, RegexOptions.IgnoreCase);
//Now that it's split, it's split a number of times that matches how many matches we found, plus one
// (The "Left over" is the +1
int HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the first sentence, {0} '{1}'.", HowMany, WhatToFind));
//Do all this again for the second example. Note that ideally, this would be in a separate function
// and you wouldn't be writing code twice, but I wanted you to see it without all the comments so you can
// compare and contrast
SplitSentences = Regex.Split(MultipleSentencesToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
SubSplitSentence = Regex.Split(SplitSentences[0], WhatToFind, RegexOptions.IgnoreCase | RegexOptions.Singleline);
HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the second sentence, {0} '{1}'.", HowMany, WhatToFind));
}
Here is the output:
We found, in the first sentence, 3 'a'.
We found, in the second sentence, 4 'a'.
You didn't define "sentence", but if we assume it's always terminated by a period (.), just add this inside the loop:
if (a == '.') {
break;
}
Expand from this to support other sentence delimiters.
Simply "break" the foreach(...) loop when you encounter a "." (period)
Well, assuming you define a sentence as being ended with a '.''
Use String.IndexOf() to find the position of the first '.'. After that, searchin a SubString instead of the entire string.
find the place of the '.' in the text ( you can use split )
count the 'a' in the text from the place 0 to instance of the '.'
string SentenceToCheck = "Hi, I can wonder this situation where I can do best";
//Here I am giving several way to find this
//Using Regular Experession
int HowMany = Regex.Split(SentenceToCheck, "a", RegexOptions.IgnoreCase).Length - 1;
int i = Regex.Matches(SentenceToCheck, "a").Count;
// Simple way
int Count = SentenceToCheck.Length - SentenceToCheck.Replace("a", "").Length;
//Linq
var _lamdaCount = SentenceToCheck.ToCharArray().Where(t => t.ToString() != string.Empty)
.Select(t => t.ToString().ToUpper().Equals("A")).Count();
var _linqAIEnumareable = from _char in SentenceToCheck.ToCharArray()
where !String.IsNullOrEmpty(_char.ToString())
&& _char.ToString().ToUpper().Equals("A")
select _char;
int a =linqAIEnumareable.Count;
var _linqCount = from g in SentenceToCheck.ToCharArray()
where g.ToString().Equals("a")
select g;
int a = _linqCount.Count();

Categories