String find and replace - c#

I have a string like
string text="~aaa~bbb~ccc~bbbddd";
The input value will be : bbb
So in the above string i should remove the value "~bbb"
The resulting string should be
text="~aaa~ccc~bbbddd";

I'm not sure what are you wanna do but if i've got it you can do this :
private string ReplaceFirstOccurrence(string Source, string Find, string Replace)
{
int Place = Source.IndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
var result =ReplaceFirstOccurrence(text,"~"+input,"");

One way would be:
string text = "~aaa~bbb~ccc~bbbddd";
string newStr = string.Join("~", text.Split('~').Where(r => r != "bbb"));
But if performance is the consideration then consider some other solution

You can use the regular expression #"\bMYWORDTOREPLACE\b" in c# this would be...
using System.Text.RegularExpressions;
myString = Regex.Replace(myString, #"\bbbb\b", "", RegexOptions.IgnoreCase);

This should do the trick:
string searchValue = "bbb";
text = text.Replace(String.Format("~{0}~", searchValue), "~");
Be sure to search for the ending ~ character as well, otherwise you will also replace part of ~bbbddd.

Like this
string str = "~rajeev~ravi";
string strRemove = "rajeev";
string strNew =str.Replace("~"+strRemove ,"");

public static string Replace(this String str, char[] chars, string replacement)
{
StringBuilder output = new StringBuilder(str.Length);
bool replace = false;
if (chars.Length - 1 < 1)
{
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
replace = false;
// int val = Regex.Matches(ch.ToString(), #"[a-zA-Z]").Count;
for (int j = 0; j < chars.Length; j++)
{
if (chars[j] == c)
{
replace = true;
break;
}
}
if (replace)
output.Append(replacement);
else
output.Append(c);
}
}
else
{
int j = 0;
int truecount = 0;
char c1 = '\0';
for (int k = 0; k < str.Length; k++)
{
c1 = str[k];
if (chars[j] == c1)
{
replace = true;
truecount ++;
}
else
{
truecount = 0;
replace = false;
j = 0;
}
if(truecount>0)
{
j++;
}
if (j > chars.Length-1)
{
j = 0;
}
if (truecount == chars.Length)
{
output.Remove(output.Length - chars.Length+1, chars.Length-1);
// output.Remove(4, 2);
if (replace)
output.Append(replacement);
else
output.Append(c1);
}
else
{
output.Append(c1);
}
}
}
return output.ToString();
}
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string word = (Console.ReadLine());
Console.WriteLine("Enter a word to find");
string find = (Console.ReadLine());
Console.WriteLine("Enter a word to Replace");
string Rep = (Console.ReadLine());
Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
Console.ReadLine();
}
}

This is an old question, but my solution is to create extension function for string.
Like ".ReplaceFirst" Java method.
You need to create static class like Helper and inside that class create static extension function:
public static class Helpers
{
public static string ReplaceFirst(this String str, string find, string replace)
{
int place = str.IndexOf(find);
if (place < 0)
{
return str;
}
//return str.Substring(0, place) + replace + str.Substring(place + find.Length);
return str.Remove(place, find.Length).Insert(place, replace);
}
}
Usage is same like .Replace method...
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", ""); //text="~aaa~ccc~bbbddd"
or more
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", "").ReplaceFirst("~bbb", ""); //text="~aaa~cccddd"

Well, you could do something like this.
(You only need to input 'bbb')
string text = "~aaa~bbb~ccc~bbbddd";
string input = "bbb";
string output = text.Replace("~" + input + "~", "~");
Console.WriteLine(output);
Output: ~aaa~ccc~bbbddd

Related

Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program

This is the code I'll try. But I got wrong output. Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program.
namespace Uncensor
{
class Program
{
// "*h*s *s v*ry *tr*ng*", "Tiiesae" ➜ "This is very strange"
static string uncensor(string str,string s)
{
string s1 = "";
int i, j;
if (str.Contains("*"))
{
for (i = 0; i < str.Length; i++)
{
if (str[i] == '*')
{
for (j = 0; j < s.Length; j++)
{
s1 = str.Replace(str[i], s[j]);
}
}
}
return s1;
}
else
{
return str;
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter string:");
string str = Console.ReadLine();
Console.WriteLine("Enter string to be replaced by * :");
string s = Console.ReadLine();
string original_text= uncensor(str, s);
Console.WriteLine(original_text);
Console.Read();
}
}
}
This is easy with linq:
string a = "*h*s *s v*ry *tr*ng*";
string b = "Tiiesae";
int index = 0;
string c = new string(a.Select(x => x == '*' ? b[index++] : x).ToArray());
public string solve(string str, string s)
{
int index = 0;
for(int i = 0; i < str.Length; ++i)
{
if(str[i] == '*') {
str[i] = s[index];
++index;
}
return str;
}

how to ignore characters when copying from one string to another - c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
How can I ignore characters between /* */ in string when copying to another string?
string str1 = "/*TODO:if*/";
How to ignore the caracters between /**/ so the new string will look like this:
string str2 = "/**/";
I am not allowed to use any library functions!
string str2 = Regex.Replace(str1, #"/\*.*\*/", "/**/");
Using a regular expression, you can capture all instances of /*[anything]*/ and replace it with just the text you want: /**/. However, this will be very greedy. If you have the string /*foo*/bar/*baz*/, this will eat all of it.
string str2 = Regex.Replace(str1, #"/\*.+?\*/", "/**/");
By changing it to be a lazy regex, the string /**/bar/**/ will be returned.
Given the edit above, this could also be done without Regex by doing a simple index search - though it is a greedy replacement.
string str2 = str1.Substring(0, str1.IndexOf("/*")) + "/*" + str1.Substring(str1.LastIndexOf("*/"));
This just takes everything before the first /* and then everything after the last */.
Try this code (it does not use any library function):
static string FormatString(string str) =>
RemoveAfter(str, "/*") + SubstringFrom(str, "*/");
static int IndexOf(string str, string value)
{
for (int i = 0; i < str.Length - value.Length; i++)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static int LastIndexOf(string str, string value)
{
for (int i = str.Length - value.Length; i >= 0; i--)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static string SubstringFrom(string str, string value)
{
int startIndex = LastIndexOf(str, value);
int length = str.Length - startIndex;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[startIndex + i];
}
return new string(result);
}
static string RemoveAfter(string str, string value)
{
int length = IndexOf(str, value) + value.Length;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[i];
}
return new string(result);
}
I'm not sure it makes sense that you can't use library functions, considering all functions are essentially library functions. I think the limitation here is that you can't bring in a library that doesn't already come imported in a new project. That's OK, we can do this hobbled like that. The Type string has a Split function, and failing that we can play it dirty and use indeces like it's 1995. I didn't get to test these but you should be well on your way with them. It was a fun little exercise, honestly.
Given : string str1 = "Stufftokeep/*TODO:if*/StufftokeepAgain";
string[] crazyHomework = str1.Split('/');
string result = string.Empty;
foreach(string s in crazyHomework)
{
if(s.IndexOf('*') == -1)
result += s + " "; //added a space to keep them separate
}
That gets you there using only System functions. Failing that, you can mutate the string into a lovely array of type char (which is all a string is anyway).
string result = string.Empty;
bool copy = true;
char[] array = str1.ToCharArray()
foreach(char a in array)
{
int i = array.IndexOf[a];
if(a == "/" && array.IndexOf(a) != array.Length - 1
&&
(array[a + 1] == '*' || array[a -1] == '*'))
{
copy = !copy;
}
if(copy)
result += a.ToString();
}
You'll have some space issues on that one if there isn't whitespace in the string, though.
Quick and dirty
string temp = null;
string str1 = "this shoudl remain/*TODO:if*/*/*testing again */-and so should this";
int x, y;
while ((x = str1.IndexOf("/*")) != -1)
{
if ((y = str1.IndexOf("*/")) > x)
{
temp += str1.Substring(0, x + 2) + str1.Substring(y, 2);
str1 = str1.Substring(y + 2);
continue;
}
temp += str1.Substring(y, x);
str1 = str1.Substring(x)
}
temp += str1;

C# - Check if string contains characters of another string at the same order

I would like to check if a string contains the characters of another string (returning true or false), but it needs to be in the "right" order but not necessarily contiguous.
Example:
String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword
String thirdWord = "road"; //FALSE - ARanDOmword
The word "arandomword" contains the letters of the word "road" but it's not possible to write it, because they are not at the right order.
Anyone, please?
Use regex. Something simple that passes your tests in linqpad:
void Main()
{
String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword
String thirdWord = "road";
Regex.IsMatch(secondWord,makeRegex(firstWord.ToCharArray())).Dump();
}
// Define other methods and classes here
String makeRegex(char[] chars)
{
StringBuilder sb = new StringBuilder();
foreach (var element in chars.Select(c => Regex.Escape(c.ToString()))
.Select(c => c + ".*"))
{
sb.Append(element);
}
return sb.ToString();
}
you could define an extension method like this:
public static class StringExtensions
{
public static bool ContainsWord(this string word, string otherword)
{
int currentIndex = 0;
foreach(var character in otherword)
{
if ((currentIndex = word.IndexOf(character, currentIndex)) == -1)
return false;
}
return true;
}
}
and call it as expressive as:
String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword
String thirdWord = "road"; //FALSE - ARanDOmword
var ret = secondWord.ContainsWord(firstWord); // true
var ret2 = thirdWord.ContainsWord(firstWord); // false
Something like this?
bool HasLettersInOrder(string firstWord, string secondWord)
{
int lastPos = -1;
foreach (char c in firstWord)
{
lastPos++;
while (lastPos < secondWord.Length && secondWord[lastPos] != c)
lastPos++;
if (lastPos == secondWord.Length)
return false;
}
return true;
}
I can not check right now, but something along the lines:
int i = 0, j = 0;
while(i < first.Length && j < second.Length)
{
while(first[i] != second[j] && j < second.Length) j++;
i++;
j++
}
bool b = i == first.Length;
Thanks for all the replies. I've tried and tried and I did it my way. Definitively it's not the shortest way to do it, but at least it's working:
public static Boolean checkWords(String smallerWord, String biggerWord)
{
int position = 0;
bool gotFirst = false;
bool gotAnother = false;
int positionBigger = 0;
String word = "";
for(int positionSmaller = 0; positionSmaller < smallerWord.Length; positionSmaller++)
{
if(!gotFirst)
{
if(biggerWord.Contains(smallerWord[positionSmaller].ToString()))
{
position = biggerWord.IndexOf(smallerWord[positionSmaller].ToString());
gotFirst = true;
word = smallerWord[positionSmaller].ToString();
}
}
else
{
gotAnother = false;
positionBigger = position + 1;
while(!gotAnother)
{
if(positionBigger < biggerWord.Length)
{
if(biggerWord[positionBigger].ToString().Equals(smallerWord[positionSmaller].ToString()))
{
position = positionBigger;
gotAnother = true;
word += smallerWord[positionSmaller].ToString();
}
else
{
positionBigger++;
}
}
else
{
gotAnother = true;
}
}
}
}
if(smallerWord.Equals(word))
{
return true;
}
else
{
return false;
}
}

Removing Leading Zeros in a Char Array

I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');

csharp method that choose every second character from the word

I need a method that returns every other character in a string starting with the first character. For example, a method call with ("Java-language") returns "Jv-agae."
private static void NewMethod(string word)
{
// here comes the code
}
var str = "Java-language";
var xx = new string(str.Where((ch, index) => index % 2 == 0).ToArray());
Console.WriteLine(xx);
Or this one:
var xx = string.Join<char>("", str.Where((ch, index) => (index & 1) == 0));
probably little different then everybody else: :-)
protected static IEnumerable<char> EverySecondChar(string word)
{
for(int i = 0; i < word.Length; i += 2)
yield return word[i];
}
string result = new string(EverySecondChar("Java-language").ToArray());
Here is my suggestion for you:
private string TakeEverySecondChar(string input)
{
var result = string.Empty;
for (int i = 0; i < input.Length; i+=2)
{
result += input.Substring(i, 1);
}
return result;
}
Console.Clear();
string Lang = "Java-language";
string[] LangArr = new string[Lang.Length];
char LangChar;
for (int i = 0; i < Lang.Length; i++)
{
LangChar = Lang[i];
LangArr[i] = LangChar.ToString();
}
for (int i = 0; i < LangArr.Length; i++)
{
Console.Write(LangArr[i]);
i++;
}
Console.ReadLine();
public String strip2ndchar(string text)
{
string final="";
int i = 0;
foreach (char a in text.ToCharArray())
{
if (i % 2 == 0)
final += a;
i++;
}
return final;
}

Categories