How to replace a char with another char without using string.replace? - c#

I want to find all occurrences of a char for ex. "H" inside of a longer string "The Haunting of Hill House". I am using this code but I am only searching by a specific position.
static void Main(string[] args)
{
string str = "The Haunting of Hill House!";
Console.WriteLine("String: " + str);
// replacing character at position 7
int pos = 7;
char rep = 'p';
string res = str.Substring(0, pos) + rep + str.Substring(pos + 1);
Console.WriteLine("String after replacing a character: " + res);
Console.ReadLine();
}

One Line solution using Linq without using string.Replace(),
string result = string.Join("", str.Select(x => x == 'H' ? 'p' : x));
`
If you want to replace whole string then try this
string result1 = string.Join(" ", str.Split(' ').Select(x => x == "Hill" ? "Zill" : x));
Input:
The Haunting of Hill House!
Output:
The paunting of pill pouse!
The Haunting of Zill House!
//^^^^ Replaced word from Hill to Zill
.net Fiddle

The general approach first find the string position you want to replace on other string with String.IndexOf function then slice the string from the position to length of string you want to replace than just insert the string with string.insert function.

Related

last and first word in a string c#

i need to print the first and the last word in a string here is what i've tried
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string first = str.Substring(0, str.IndexOf(" "));
string last = str.Substring(str.LastIndexOf(' '),str.Length-1);
Console.WriteLine(first + " " + last);
when i run the code this massage appear
Unhandled Exception: 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 ConsoleApp1.Tar13.Main() in C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16
i dont know what is the problem
If this is homework, don't hand this in unless you really understand it, have done LINQ (or have a supervisor that approves of off-piste learning and you're prepared to acknowledge you got outside assistance/did background learning) and are willing to explain it if asked:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string[] bits = str.Split();
Console.WriteLine(bits.First() + " " + bits.Last());
For a non-LINQ version:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string first = str.Remove(str.IndexOf(' '));
string last = str.Substring(str.LastIndexOf(' ') + 1);
Console.WriteLine(first + " " + last);
Bear in mind that these will crash if there are no spaces in the string - the Split version won't
Look at String Remove and Substring
If you want to robust things up so it doesn't crash:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
if(str.Contains(" ")){
string first = str.Remove(str.IndexOf(' '));
string last = str.Substring(str.LastIndexOf(' ') + 1);
Console.WriteLine(first + " " + last);
}
I'll leave a "what might we put in an else?" in that last code block, as an exercise for you :)
you can split the string and get first and last...
var s = str.Split(' ', StringSplitOptions.RemoveEmptyEntries );
if(s.Length >= 2)
{
var first = s.First();
var last = s.Last();
Console.WriteLine($"{first} {last}");
}
In general case when sentence can contain punctuation, not necessary English letters you can try regular expressions. Let's define
Word is non empty sequence of letters and apostrophes
And so we have
Code:
using System.Linq;
using System.Text.RegularExpressions;
...
private static (string first, string last) Solve(string value) {
if (string.IsNullOrWhiteSpace(value))
return ("", "");
var words = Regex
.Matches(value, #"[\p{L}']+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
return words.Length > 0
? (words[0], words[words.Length - 1])
: ("", "");
}
Demo:
string[] tests = new string[] {
"Simple string", // Simple Smoke Test
"Single", // Single word which is both first an last
"", // No words at all; let's return empty strings
"words, punctuations: the end.", // Punctuations
"Русская (Russian) строка!", // Punctuations, non-English words
};
var result = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-30} :: {Solve(test)}"));
Console.Write(result);
Outcome:
Simple string :: (Simple, string)
Single :: (Single, Single)
:: (, )
words, punctuations: the end. :: (words, end)
Русская (Russian) строка! :: (Русская, строка)
If you want to get the last and first-word try to do the following:
string sentence = "Hello World"; //Sentence
string first = sentence.Split(" ")[0]; //First word
string last = sentence.Split(" ")[sentence.Split(" ").Length -1]; //Last word
Console.WriteLine(first + " "+ last);

What is the correct syntax of adding white space after specified number of characters using regex.replace()?

I'm using Regex.Replace to add a white space after every nth character into a string. I want to give an int variable(number of characters) after which white space should be added but It seems regular expression is not properly written for int variable and hence syntax error arises.
int num = 8;
string text="abcdefghijklmnop"
string result2 = Regex.Replace(text, ".{num}", "$0 "); //not working
this syntax is working
string result2 = Regex.Replace(text, ".{8}", "$0 ");
Regular expressions aren't parameterized in the way that you want, as far as I'm aware. Instead, you need to just build the pattern appropriately.
For most situations in modern C# I'd suggest using an interpolated string literal, which does work in this case, but requires the { and } to be doubled to avoid being treated as format specifiers. It may be more readable to just use string concatenation. So you can either use:
string result = Regex.Replace(text, ".{" + num + "}", "$0 ");
or if you're comfortable with { having different meanings in the same literal:
string result = Regex.Replace(text, $".{{{num}}}", "$0 ");
Not sure exactly what you want, but you may build the regex pattern using string concatenation:
int num = Int32.Parse(text_num);
string regex = ".{" + num + "}";
string result2 = Regex.Replace(text, regex, "$0 ");
TextArea1_trim_id.InnerText = result2;
This answer says nothing regarding whether your regex pattern makes any sense or is correct.
Alternative Linq solution (no regular expressions): we insert " " after each num characters (c)
int num = 8;
string text = "abcdefghijklmnop";
// "abcdefgh ijklmnop "
string result2 = string.Concat(text
.Select((c, i) => (i + 1) % num == 0
? c.ToString() + " "
: c.ToString()));
If we don't want to add trailing spaces (and thus we want "abcdefgh ijklmnop")
string result2 = string.Concat(text
.Select((c, i) => i < text.Length - 1 && (i + 1) % num == 0
? c.ToString() + " "
: c.ToString()));

Reverse Words at odd position only C#

This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
Example input:
"How are you today"
to output:
"How era you yadot"
Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
inputWords.Select((w, i) =>
i % 2 == 0
? w
: new string(w.Reverse().ToArray())
));
Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online
So far you have a string, like this:
string input = "I want to reverse all odd words (odd words only!).";
And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
using System.Linq; // To reverse single word
using System.Text.RegularExpressions; // To match the words within the text
...
// Let's elaborate the test example: add
// 1. some punctuation - ()!. - to preserve it
// 2. different white spaces (spaces and tabulation - \t)
// to add difficulties for naive algorithms
// 3. double spaces (after "to") to mislead split based algorithms
string input = "I want to reverse all\todd words (odd words only!).";
int index = 0; // words' indexes start from zero
string result = Regex.Replace(
input,
"[A-Za-z']+", // word is letters and apostrophes
match => index++ % 2 == 0
? match.Value // Even words intact
: string.Concat(match.Value.Reverse())); // Odd words reversed
Console.WriteLine(result);
If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
match => match.Value % 2 == 0
Outcome:
I tnaw to esrever all ddo words (ddo words ylno!).
Please, notice, that the punctuation has been preserved (only words are reversed).
OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
string input = "How are you today Laken-C";
//As pointed out by #Dmitry Bychenko string input = "How are you today";
//(double space after How) leads to How are uoy today outcome
input = Regex.Replace(input, #"\s+", " ");
var inp = input.Split(' ').ToList();
for (int j = 0; j < inp.Count(); j++)
{
if(j % 2 == 1)
{
Console.Write(inp[j].Reverse().ToArray());
Console.Write(" ");
}
else
Console.Write(inp[j] + " ");
}
}
OUTPUT:
DEMO:
dotNetFiddle
try this is perfect working code..
static void Main(string[] args)
{
string orgstr = "my name is sagar";
string revstr = "";
foreach (var word in orgstr.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
revstr = revstr + temp + " ";
}
Console.Write(revstr);
Console.ReadKey();
}
Output: ym eman si ragas

c# finding indexof and remove character atsign

there is a String which contains some # characters, i want to find " # " in my string and remove them, but it also finds and removes these ones: "#"
int atsignPlace = str.IndexOf(" # ");
while (atsignPlace >= 0)
{
str = str.Remove(atsignPlace,3);
atsignPlace = str.IndexOf(" # ");
}
i tried this code, but it removes nothing, so it always finds first '#' ,which makes it an infinite loop.
int atsignPlace = str.IndexOf(" #");
while (atsignPlace >= 0)
{
if( atsignPlace+1 < str.Length && str[atsignPlace+1] == ' ' )
str = str.Remove(atsignPlace,3);
atsignPlace = str.IndexOf(" # ");
}
Replace method also doesn't work correct.
str = str.Replace(" # ", String.Empty);
maybe there is a problem with '#' character.
the input string is a sql query, i am trying to remove some parameters from it.
[ i have used try-catch for exceptions ]
Your code works fine. Short but complete program to demonstrate:
using System;
class Test
{
static void Main()
{
string before = "xyz # abc#123";
string after = CustomRemove(before);
Console.WriteLine(after); // Prints xyzabc#123
}
static string CustomRemove(string text)
{
int atSignIndex = text.IndexOf(" # ");
while (atSignIndex >= 0)
{
text = text.Remove(atSignIndex, 3);
atSignIndex = text.IndexOf(" # ");
}
return text;
}
}
EDIT: Of course, Replace works fine too:
using System;
class Test
{
static void Main()
{
string before = "xyz # abc#123";
string after = before.Replace(" # ", "");
Console.WriteLine(after); // Prints xyzabc#123
}
}
If you're still seeing a problem with either of these, then the issue is in how you're using this code, not in the code itself.
One guess: you might have non-printed characters within the " # " which is preventing them from being removed. But you haven't really given us enough information to say. A short but complete program demonstrating it not working would help...
Keep it simple:
string result = input.Replace(" # ", String.Empty);
MSDN: String.Replace Method (String, String)
I would use regex to make sure that you get any number of whitespaces:
Regex.Replace(input, #"\s+#\s+", m => string.Empty);
string LclString = "#12 # 123#123 # #";
LclString = LclString.Replace(" # ", " ");
Yields this:
#12 123#123 #

Adding a '-' to my string in C#

I Have a string in the form "123456789".
While displaying it on the screen I want to show it as 123-456-789.
Please let me knwo how to add the "-" for every 3 numbers.
Thanks in Advance.
You can use string.Substring:
s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3);
or a regular expression (ideone):
s = Regex.Replace(s, #"\d{3}(?=\d)", "$0-");
I'll go ahead and give the Regex based solution:
string rawNumber = "123456789";
var formattedNumber = Regex.Replace(rawNumber, #"(\d{3}(?!$))", "$1-");
That regex breaks down as follows:
( // Group the whole pattern so we can get its value in the call to Regex.Replace()
\d // This is a digit
{3} // match the previous pattern 3 times
(?!$) // This weird looking thing means "match anywhere EXCEPT the end of the string"
)
The "$1-" replacement string means that whenever a match for the above pattern is found, replace it with the same thing (the $1 part), followed by a -. So in "123456789", it would match 123 and 456, but not 789 because it's at the end of the string. It then replaces them with 123- and 456-, giving the final result 123-456-789.
You can use for loop also if the string length is not fixed to 9 digits as follows
string textnumber = "123456789"; // textnumber = "123456789012346" also it will work
string finaltext = textnumber[0]+ "";
for (int i = 1; i < textnumber.Length; i++)
{
if ((i + 1) % 3 == 0)
{
finaltext = finaltext + textnumber[i] + "-";
}
else
{
finaltext = finaltext + textnumber[i];
}
}
finaltext = finaltext.Remove(finaltext.Length - 1);

Categories