I'm pretty familiar with finding and replacing things in an array, but I'm having trouble finding out how to replace specific parts of a string. For instance, say the first item in my array is a string of sixteen random numbers like 1786549809654768. How would I go about replacing the first twelve characters with x's for example?
Because string can be translated to and from an array of char you could easily transform your problem into replace things in an array problem:
char[] characters = input.ToCharArray();
// do your replace logic here
string result = new string(characters);
Or you could use Substring. Assuming n is number of characters you want to replace from the beginning or the string:
string result = new string('x', n) + input.Substring(n);
You can use Linq:
String test = "1234123412341234";
string output = new String(test.Select((c, index) => index < 12 ? 'x' : c).ToArray());
Console.WriteLine(output);
//xxxxxxxxxxxx1234
Related
I have this alphabet array and a word:
string Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Array alphabet = Digits.ToCharArray();
string target = "ABC?0";
I want to check if target contains a character which is not available in the alphabet array and if so, print the character. So in the above example, there are two characters available in target and not available in alphabet ("0" and "?").
How can I do that ?
You don't need ToCharArray. Simply just use the Except method like this:
var result = target.Except(Digits).ToArray();
And if you still need to use alphabet, change it's type to char[]:
char[] alphabet = Digits.ToCharArray();
var result = target.Except(alphabet).ToArray();
And if you would like to see the result as string, you can use string.Join like this:
var result = string.Join("", target.Except(Digits));
Just make sure that using System.Linq; has been already added to your using statements.
if(alphabet.Contains(target))
{
// do some work
}
Also check this link : How to check if a particular character exists within a character array
There is an array of characters e.g.
char [] biggerText = new char [8];
then I input some values likewise:
biggerText[0] = (char) 12;
biggerText[1] = (char) 48;
then I use the following operation:
string smallerText= string.Join("", biggerText);
and when you perform smallerText.Length you get 8 and NOT 2.
What is the most effective method to trim this array to omit the null values when converting to string?
Why don't you use a List<char>? This way, you don't have to worry about indexes, and you don't have to know the final length at the beginning (as pointed out in the comment by #n8wrl).
var list = new List<char>();
list.Add((char)12);
list.Add((char)48);
Then you can get the final string in a more elegant way:
var smallerText = new string(list.ToArray());
And this string will have the correct Length.
This should do the trick.
string smallerText = string.Join("", biggerText.Where(n => n != '\0'));
This is a good way to do it, because Trim will work just with white spaces and may not work well for you.
You can make a new string from the array and trim the null chars from the end:
string smallerText = new String(biggerText).TrimEnd('\0');
You can use TakeWhile to only take the characters until you see a "null" character assuming you don't want any of the characters that might exist after the first "null" character.
string smallerText= string.Join("", biggerText.TakeWhile(c => c != '\0'));
char [] biggerText = new char [8];
biggerText[0] = (char)12;
biggerText[1] = (char)48;
string smallerText= new string(biggerText).Replace("\0", string.Empty);
int length = smallerText.Length;
\0 can be at any location, so just replace it with empty value.
If you mean the most efficient:
string smallerText = new string(biggerText, 0, 2);
but "the most effective method to trim" is the .Trim method 😊
string smallerText = new string(biggerText).TrimEnd(char.MinValue);
Have an assignment to allow a user to input a word in C# and then display that word with the first and third characters changed to uppercase. Code follows:
namespace Capitalizer
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
char[] delimiterChars = { ' ' };
string[] words = text.Split(delimiterChars);
string Upper = text.ToUpper();
Console.WriteLine(Upper);
Console.ReadKey();
}
}
}
This of course generates the entire word in uppercase, which is not what I want. I can't seem to make text.ToUpper(0,2) work, and even then that'd capitalize the first three letters. Only solution I can think of now that would make the word appear on one line (and I don't know if it works) is to move the capitalized letters and lowercase letters into a character array and try to get that to print all values in a modified order.
The simplest way I can think of to address your exact question as described — to convert to upper case the first and third characters of the input — would be something like the following:
StringBuilder sb = new StringBuilder(text);
sb[0] = char.ToUpper(sb[0]);
sb[2] = char.ToUpper(sb[2]);
text = sb.ToString();
The StringBuilder class is essentially a mutable string object, so when doing these kinds of operations is the most fluid way to approach the problem, as it provides the most straightforward conversions to and from, as well as the full range of string operations. Changing individual characters is easy in many data structures, but insertions, deletions, appending, formatting, etc. all also come with StringBuilder, so it's a good habit to use that versus other approaches.
But frankly, it's hard to see how that's a useful operation. I can't help but wonder if you have stated the requirements incorrectly and there's something more to this question than is seen here.
You could use LINQ:
var upperCaseIndices = new[] { 0, 2 };
var message = "hello";
var newMessage = new string(message.Select((c, i) =>
upperCaseIndices.Contains(i) ? Char.ToUpper(c) : c).ToArray());
Here is how it works. message.Select (inline LINQ query) selects characters from message one by one and passes into selector function:
upperCaseIndices.Contains(i) ? Char.ToUpper(c) : c
written as C# ?: shorthand syntax for if. It reads as "If index is present in the array, then select upper case character. Otherwise select character as is."
(c, i) => condition
is a lambda expression. See also:
Understand Lambda Expressions in 3 minutes
The rest is very simple - represent result as array of characters (.ToArray()), and create a new string based off that (new string(...)).
Only solution I can think of now that would make the word appear on one line (and I don't know if it works) is to move the capitalized letters and lowercase letters into a character array and try to get that to print all values in a modified order.
That seems a lot more complicated than necessary. Once you have a character array, you can simply change the elements of that character array. In a separate function, it would look something like
string MakeFirstAndThirdCharacterUppercase(string word) {
var chars = word.ToCharArray();
chars[0] = chars[0].ToUpper();
chars[2] = chars[2].ToUpper();
return new string(chars);
}
My simple solution:
string text = Console.ReadLine();
char[] delimiterChars = { ' ' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
char[] chars = s.ToCharArray();
chars[0] = char.ToUpper(chars[0]);
if (chars.Length > 2)
{
chars[2] = char.ToUpper(chars[2]);
}
Console.Write(new string(chars));
Console.Write(' ');
}
Console.ReadKey();
Okay, lets say I have a string:
string text = "one|two|three";
If I do string[] texts = text.Split('|'); I will end up with a string array of three objects. However, this isn't what I want. What I actually want is to split the string only once... so the two arrays I could would be this:
one
two|three
Additionally, is there a way to do a single split with the last occurrence in a string? So I get:
one|two
three
As well, is there a way to split by a string, instead of a character? So I could do Split("||")
Split method takes a count as parameter, you can pass 2 in that position, which basically says that you're interested in only 2 elements maximum. You'll get the expected result.
For second question: There is no built in way AFAIK. You may need to implement it yourself by splitting all and joining first and second back.
C#'s String.Split() can take a second argument that can define the number of elements to return:
string[] texts = text.Split(new char[] { '|' }, 2);
For your first scenario, you can pass a parameter of how many strings to split into.
var text = "one|two|three";
var result = text.Split(new char[] { '|' }, 2);
Your second scenario requires a little more magic.
var text = "one|two|three";
var list = text.Split('|');
var result = new string[] { string.Join("|", list, 0, list.Length - 1), list[list.Length - 1] };
Code has not been verified to check results before using.
Well, I took it as a challenge to do your second one in one line. The result is... not pretty, mostly because it's surprisingly difficult to reverse a string and keep it as a string.
string text = "one|two|three";
var result = new String(text.Reverse().ToArray()).Split(new char[] {'|'}, 2).Reverse().Select(c => new String(c.Reverse().ToArray()));
Basically, you reverse it, then follow the same procedure as the first one, then reverse each individual one, as well as the resulting array.
You can simply do like this as well...
//To split at first occurence of '|'
if(text.Containts('|')){
beginning = text.subString(0,text.IndexOf('|'));
ending = text.subString(text.IndexOf('|');
}
//To split at last occurence of '|'
if(text.Contains('|')){
beginning = text.subString(0,text.LastIndexOf('|'));
ending = text.subString(text.LastIndexOf('|');
}
Second question was fun. I solved it this way:
string text = "one|two|three";
var result =
new []
{
string.Concat(text.ToCharArray().TakeWhile((c, i) => i <= text.LastIndexOf("|"))),
string.Concat(text.ToCharArray().SkipWhile((c, i) => i <= text.LastIndexOf("|")))
};
Say I have a string such as
abc123def456
What's the best way to split the string into an array such as
["abc", "123", "def", "456"]
string input = "abc123def456";
Regex re = new Regex(#"\D+|\d+");
string[] result = re.Matches(input).OfType<Match>()
.Select(m => m.Value).ToArray();
string[] result = Regex.Split("abc123def456", "([0-9]+)");
The above will use any sequence of numbers as the delimiter, though wrapping it in () says that we still would like to keep our delimiter in our returned array.
Note: In the example snippet we will get an empty element as the last entry of our array.
The boundary you look for can be described as "A position where a digit follows a non-digit, or where a non-digit follows a digit."
So:
string[] result = Regex.Split("abc123def456", #"(?<=\D)(?=\d)|(?<=\d)(?=\D)");
Use [0-9] and [^0-9], respectively, if \d and \D are not specific enough.
Add space around digitals, then split it. So there is the solution.
Regex.Replace("abc123def456", #"(\d+)", #" \1 ").Split(' ');
I hope it works.
You could convert the string to a char array and then loop through the characters. As long as the characters are of the same type (letter or number) keep adding them to a string. When the next character no longer is of the same type (or you've reached the end of the string), add the temporary string to the array and reset the temporary string to null.