- Home /
Replace all Characters in a String
I'm using Replace is order to replace all characters in a string with '-'. However, I do not know a way to replace all characters with dashes, only those that are specified. Here's the code:
ans = wordGen.Replace ("a", "-");
Is there any way to get it to replace all characters in the string, instead of just 'a'?
Thanks in advance
-MrFodds
Answer by asafsitner · Apr 05, 2014 at 10:01 AM
The straightforward way would be something like this (replace the old string with a new string of the same length composed of only the desired character):
string ReplaceAll(string input, char target)
{
StringBuilder sb = new StringBuilder(input.Length);
for(int i = 0; i < input.Length; i++)
{
sb.Append(target);
}
return sb.ToString();
}
Then implementation would be:
ans = ReplaceAll(wordGen, '-');
You could even go the fancy way and add an overload that takes a char list as filter, so you can do something like this:
string ReplaceAll(string input, char target, List<char> filter)
{
StringBuilder sb = new StringBuilder(input.Length);
for(int i = 0; i < input.Length; i++)
{
if(filter.Contains(input[i]))
{
sb.Append(input[i]);
}
else
{
sb.Append(target);
}
}
return sb.ToString();
}
Note that for these methods you need to import these namespaces:
using System.Text;
using System.Collections.Generic;
StringBuilder isn't working using the standard collections (It says it does not exist) Do I need to use a certain collection?
Oh, I'm sorry. Forgot to add the namespace import.
You have to add
using System.Text;
To the top of the class.
You could have tried googling it. Took me 5 seconds to find this page, which states that you need to include the System.Text
namespace.
Edited the answer to fix the 'void' return type to 'string'.
Also added overload that takes char list as mask just for the fun of it :P
Ah, was just about to ask about that. The code now works beautifully, thanks for all your help :D
Answer by Josh707 · Apr 05, 2014 at 10:09 AM
You can create an array of characters with the same length as the string, use a for loop to fill it with dashes and put that back into a string. This would replace everything but spaces:
string text = "Some text!";
char[] dashes = new char[text.Length];
for(int i=0; i<dashes.Length; i++){
dashes[i] = text[i] == ' '? ' ':'-';
//or dashes[i] = ' '; for every character
}
string output = new string(dashes);
//output would be "---- -----"
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can I replace a camera that is part of a prefab with a camera that exists in a scene? 0 Answers
Renderer on object disabled after level reload 1 Answer
Want replace a current object with one inside array the object being replaced with is prefab 1 Answer