How to replace next Character of string with immediate character - c#

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.

Related

Replace single slash in string C#

My requirement
If string contains single slash (/ or \) it should be replace with
double slash
Note :- string is randomly generated so, I have no control.
e.g. I have string
string str = #"*?i//y\^Pk#t9`n2";
When I tried as
str = str.Replace(#"\", #"\\").Replace(#"/",#"//");
it replaced // with //// but I need to replace only single slash(\) with double slash(\\).
Above code actual result is
*?i////y\^Pk#t9`n2
expected result is
*?i//y\\^Pk#t9`n2
Note :- If string contain double slash in sequence like "//" or "\\" then no need to modify string. but string contains single slash (/ or \) need to replace with double slash.
I have tried to find out other approach then I found following stack-overflow already question-answer
Replace single backslash with double backslash
Replace "\\" with "\" in a string in C#
How to change backslash to double backslash?
Question :-
How to check if string contain single slash and how to replace it?
What best practice should follows while doing string manipulation like this?
Edit :-
I have random generated string comes from user like.
string str = #"*?i//y\^Pk#t9`n2";
sometimes that string contain single slash as above (\). if we consider above string without verbatim(#) it is not a valid string in C#. it gives compile time error. to make above string valid I need to replace "\" with "\\".
How I can achieve this?
Pls try this, first i repleced all double slash with single slash and then vice versa:
var str = #"*?i//y\^Pk#t9`n2";
var tempStr = str.Replace(#"\\", #"\").Replace(#"//",#"/");
var result = tempStr.Replace(#"\", #"\\").Replace(#"/",#"//");
I had to do two Regex.Replace and use look arounds to achieve this. The final solution was
Regex.Replace(Regex.Replace(str, #"(?<!\/)\/(?!\/)", #"//"), #"(?<!\\)\\(?!\\)", #"\\")
If you've never dealt with regex before, it can be a beast. Essentially I am looking for all backslashes and forward slashes (\\ and \/ escaped) and once I match a backslash and forward slash, I am going to use negative lookbehinds and negative aheads to not match if it there is a match in front or behind it.
Negative Look Behind:
(?<!\/)
Negative Look Ahead:
(?!\/)
I am then repeating it twice for forward slashes and backwards slashes
The best solution might be to roll your own algorithm. Step through the string character by character looking for a slash, and if it finds one, check the next character and previous, if 1 of those exist, then do not insert a duplicate slash because that means it is not alone
This replaces all of the individual occurrences of a character and also fills up an odd number of occurrences:
public static string ReplaceSingle(this string s, char needle)
{
var valueSpan = s.AsSpan();
var length = valueSpan.Length * 2;
char[]? resultArray = null;
Span<char> resultSpan = length <= 256
? stackalloc char[length]
: (resultArray = ArrayPool<char>.Shared.Rent(length));
var value = char.MinValue;
var written = 0;
for (int index = 0; index < valueSpan.Length; index++)
{
value = valueSpan[index];
resultSpan[written++] = value;
if (value == needle && ++index < valueSpan.Length)
{
value = valueSpan[index];
resultSpan[written++] = value == needle ? value : needle;
}
}
var result = new string(resultSpan[..written]);
resultSpan.Clear();
if (resultArray is not null) ArrayPool<char>.Shared.Return(resultArray);
return result;
}
For instance, if you have / it will turn to //, but // will remain. However /// will turn to //// and so on.
There is also a usage of ArrayPool and stackalloc which are aimed at better performance.
Usage:
string value = "This/ is a //Test ///!";
string result = value.ReplaceSingle('/');

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

Perform Select at odd positions in the string

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)));

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.

How can get a substring from a string in C#?

I have a large string and it’s stored in a string variable, str. And I want to get a substring from that in C#.
Suppose the string is: " Retrieves a substring from this instance. The substring starts at a specified character position, "
The substring result what I want to display is: The substring starts at a specified character position.
You could do this manually or using the IndexOf method.
Manually:
int index = 43;
string piece = myString.Substring(index);
Using IndexOf, you can see where the full stop is:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
string newString = str.Substring(0, 10);
will give you the first 10 characters (from position 0 to position 9).
See String.Substring Method.
Here is an example of getting a substring from the 14th character to the end of the string. You can modify it to fit your needs.
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
// Get substring where 14 is the start index
string substring = text.Substring(14);
Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurrences:
// Add # to the string to allow split over multiple lines
// (for display purposes to save the scroll bar from
// appearing on a Stack Overflow question :))
string strBig = #"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// Split the string on the full stop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
.Where(x => x.Length > 0).Select(x => x.Trim());
// Iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
Console.WriteLine(subword);
}
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
This will cut the part of string which lays between the special characters.
A better solution using index in C# 8:
string s = " Retrieves a substring from this instance. The substring starts at a specified character position, ";
string subString = s[43..^2]; // The substring starts at a specified character position
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
var result = data.Split(new[] {'.'}, 1)[0];
Output:
Retrieves a substring from this instance. The substring starts at a
specified character position.
All answers used the main string that decrease performance. You should use Span to have better performance:
var yourStringSpan = yourString.AsSpan();
int index = yourString.IndexOf(".") + 1;
string piece = yourStringSpan.slice(index);
It's easy to rewrite this code in C#...:
This method works if your value is between two substrings!
For example:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
The calls should be:
myNameValue = SplitStringByASubstring(stringContent, "[myName]")
colorValue = SplitStringByASubstring(stringContent, "[color]")
etcValue = SplitStringByASubstring(stringContent, "[etc]")

Categories