String manuplation in C# - c#

Is there any method that I can use that returns a fixed length array after spliting a string with some delimiter and fill the rest with a default string.
Eg.
string fullName = "Jhon Doe";
string[] names = fullName.SpecialSplit(some parameters); //This should always return string array of length 3 with the second elememnt set to empty if there is no middle name.

Next time specify the language you're asking about. We're no guessers.
In Java:
fullName.split(" ");
And anyway, no method will "return string array of length 3 with the second elememnt set to empty if there is no middle name". For the method, there are just two elements. You have to write that method yourself wrapping the standard split() method.

You should read over Jon Skeet's Writing the perfect question. It will be beneficial to you in the future when posting questions of StackOverflow.
There is no method in C# to do what you are asking, but you can easily write an extension method to do what I think you are asking.
here is a quick example:
public static class AbreviatorExtention
{
public static string[] GetInitials(this String str, char splitChar)
{
string[] initialArray = new string[3];
var nameArray = str.Split(new char[] { splitChar },
StringSplitOptions.RemoveEmptyEntries);
if (nameArray.Length == 2)
{
var charArrayFirstName = nameArray[0].ToCharArray();
var charArrayLastName = nameArray[1].ToCharArray();
initialArray[0] = charArrayFirstName[0].ToString().ToUpper();
initialArray[1] = string.Empty;
initialArray[2] = charArrayLastName[0].ToString().ToUpper();
}
else
{
for (int i = 0; i < nameArray.Length; i++)
{
initialArray[i] = (nameArray[i].ToCharArray())[1]
.ToString().ToUpper();
}
}
return initialArray;
}
}
class Program
{
static void Main(string[] args)
{
string FullName = "john doe";
//Extension method in use
string[] names = FullName.GetInitials(' ');
foreach (var item in names)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
Output:
J
D

I would set it up to split the string separate from the fixed array. If you still want a fixed array, then you set up the array to a size of three an populate. This is not the best method, however, as it has no meaning. Better, set up a person or user class and then populate, via rules, from the split string.

Related

What Is The Difference Between CharArray.ToString and new String(cArray)? [duplicate]

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

c# Working with Strings

I'm Learning c# and i am making some exercises. i was asked to make a program that make an array of strings and remove the vowels form it's words
i did this code to remove the vowel "S" but it didn't work. can someone help me with that ?
string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };
foreach (string s in musicinst)
{
if (s.Contains("s")) { s.Replace("s", ""); }
Console.WriteLine(s);
}
now this code outputs the words exactly as i typed them in the array with no changes. so what is the problem here ?
.Replace does not change the string but returns a new string with the change. You need to now assign it back to s:
if (s.Contains("s"))
{
s = s.Replace("s", "o");
}
This will now also not work:
Cannot assign to 's' because it is a 'foreach iteration variable'
So instead use a for loop and access by indexer or create a new list and add the result of s.Replace to it:
string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };
var newData = musicinst.Select(item => item.Replace("s", "o")).ToArray();
If you need to deal with replacement when insensitive then look at:
Is there an alternative to string.Replace that is case-insensitive?
You're running into a feature of C# strings called immutability - operations on strings do not change the string, it returns a new string. given this, you might think you need to do this:
s = s.Replace("s", "o");
But that won't work because 's' is a foreach iterator. Your best bet is to recast your loop:
for (int i = 0; i < musicinst.Length; ++i)
{
if (musicinst[i].Contains("s"))
{
musicinst[i] = musicinst.Replace("s", "o");
}
}
Which will change your array in-place. To preserve immutability of the array as well you might consider a LINQ-like option that builds a new array as others have demonstrated.
static void Main(string[] args)
{
string[] musicinst = new string[4] { "cello", "guitar", "violin", "double bass" };
char[] vowels = new char[5] { 'a', 'e', 'i' ,'o', 'u' };
List<string> output = new List<string>();
foreach (string s in musicinst)
{
string s1 = s;
foreach (var v in vowels)
{
if (s1.Contains(v))
{
s1=s1.Remove(s1.IndexOf(v),1);
}
}
output.Add(s1);
}
Console.ReadLine();
}
Whenever you perform any operation on a string data type, it creates a new string which you have to store in a new variable.

Turn a string of '"a", "b", "c"' into an array of strings

Please read the specifics below:
I have a string array as so:
string[] data = new string[] { "word1", "word2", "word3" };
I'm trying to put a STRING variable, which will include the "word1", "word2", "word3" data, inside of the string array.
In other words, I want the string array to look as so:
SingleStringHere = "\"word1\", \"word2\", \"word3\"";
string[] data = new string[] { SingleStringHere };
The 'SingleStringHere' variable will be retrieving data off of a server, which will be used in the string array. The string array will be formatted and encrypted properly, in order to be sent in a packet through a socket.
No errors are given with the code, however, data in the 'SingleStringHere' variable is not being read as separate strings. I do NOT want to put the retrieved server data into a string array, because that will be TOO MUCH parsing!
If the strings that you receive don't contain commas, you could do something as simple as this:
string SingleStringHere = "\"word1\", \"word2\", \"word3\"";
string[] data = SingleStringHere.Replace("\"").Split(',');
Otherwise, you're going to have to do some more complex parsing. Something like this:
static void Main(string[] args)
{
string SingleStringHere = "\"word1\", \"word2\", \"word3\"";
string[] data = ParseSingleString(SingleStringHere);
foreach(string s in data)
{
Console.WriteLine(s);
}
}
public static string[] ParseSingleString(string singleString)
{
List<string> multipleStrings = new List<string>();
StringBuilder current = new StringBuilder();
bool inQuote = false;
for(int index = 0; index < singleString.Length; ++index) // iterate through the string
{
if (singleString[index] == '"')
{
inQuote = !inQuote;
}
else if (!inQuote && singleString[index] == ',') // split at comma if not in quote
{
multipleStrings.Add(current.ToString().Trim());
current.Clear();
}
else
{
current.Append(singleString[index]);
}
}
multipleStrings.Add(current.ToString()); // don't forget the last one
return multipleStrings.ToArray();
}
If the strings can contain quotes, it can get trickier. That's just my rough example.
Be warned that this operation might be memory-intensive with all of the string copying and so forth (I count about 3 copies for each substring). You may be able to circumvent some of this by recording the indices of the first and last character in one of the strings, and then taking a substring on the entire singleString. Also note that List<string> has to be copied into an array before it returns. You may want to just return an IEnumerable<string> instead, or even an IList<string>. But it's late, and I think the above is sufficient for this question.
P.s. I'm on a Linux machine right now without access to a C# compiler, so I apologize for any typos.
You can get array from formatted string like this
string SingleStringHere = "\"word1\", \"word2\", \"word3\"";
String[] arr = SingleStringHere.Split(',');

How can you put single spaces into a string of characters in C#

I am still a beginner in C# and I know there is a method that can be used to do this but I can't seem to find it online.
I have a function that permutates a word
static void Main(string[] args)
{
string[] list = "a b c d".Split();
foreach (string[] permutation in Permutations<string>.AllFor(list))
{
System.Console.WriteLine(string.Join(" ", permutation));
}
}
However it only works with words that are broken up. (eg. "a b c d" ) Since that is not really a practical way to ask a user for input, I want to find a way to take a word from the user (an unbroken word like "hello" ) and break it up for the function to understand. Eg. form the input word of the use "happy" to a spaced word for the program to understand = "h a p p y"
I tried this code:
//splits the word into an array
string[] arr = name.Split();
//splits the array with spaces to enter into the program
name = string.Join(" ",arr);
arr = name.Split();
But it just ends up coming out unbroken anyway. Can someone tell me the easiest way to do this?
Just to mention I am still a beginner in C# and programming in total I might not understand some of the higher level concepts. I have been through some answers on this website and I have seen some answers that I don't understand at all.
You can loop over the string to convert it to an array, and then use Join.
using System.Text.RegularExpressions;
using System;
public class Program{
public static void Main(string[] args) {
string v = "hello";
// Convert into the a string array, the old-fashioned way.
string[] name = new string[v.Length];
for (int i = 0; i < v.Length; i++)
name[i] = v[i] + "";
string feedToPermutationFunction = string.Join(" ",name));
// Feed the above string into your permutation code.
}
}
You just need to separate each character and then concatenate them with a space:
This is the simplest way:
var userInput = Console.ReadLine();
var output = string.Join<char>(" ", userInput);
Console.WriteLine(output);
char[] array=input.ToArray();
string val="";
for(int i=0;i<array.Length;i++)
{
val+=array[i]+" ";
}
this will give you a string with spaces like you wanted Val
create an array with the string length
string[] strarray=new string[val.Length];
for(int i=0;i<strarray.Length;i++)
{
strarray[i]=val.Substring(i,len); //**i** is for string index,,,**len** string length in each index
}

Removing duplicate substrings within a string in C#

How can I remove duplicate substrings within a string? so for instance if I have a string like smith:rodgers:someone:smith:white then how can I get a new string that has the extra smith removed like smith:rodgers:someone:white. Also I'd like to keep the colons even though they are duplicated.
many thanks
string input = "smith:rodgers:someone:smith:white";
string output = string.Join(":", input.Split(':').Distinct().ToArray());
Of course this code assumes that you're only looking for duplicate "field" values. That won't remove "smithsmith" in the following string:
"smith:rodgers:someone:smithsmith:white"
It would be possible to write an algorithm to do that, but quite difficult to make it efficient...
Something like this:
string withoutDuplicates = String.Join(":", myString.Split(':').Distinct().ToArray());
Assuming the format of that string:
var theString = "smith:rodgers:someone:smith:white";
var subStrings = theString.Split(new char[] { ':' });
var uniqueEntries = new List<string>();
foreach(var item in subStrings)
{
if (!uniqueEntries.Contains(item))
{
uniqueEntries.Add(item);
}
}
var uniquifiedStringBuilder = new StringBuilder();
foreach(var item in uniqueEntries)
{
uniquifiedStringBuilder.AppendFormat("{0}:", item);
}
var uniqueString = uniquifiedStringBuilder.ToString().Substring(0, uniquifiedStringBuilder.Length - 1);
Is rather long-winded but shows the process to get from one to the other.
not sure why you want to keep the duplicate colons. if you are expecting the output to be "smith:rodgers:someone::white" try this code:
public static string RemoveDuplicates(string input)
{
string output = string.Empty;
System.Collections.Specialized.StringCollection unique = new System.Collections.Specialized.StringCollection();
string[] parts = input.Split(':');
foreach (string part in parts)
{
output += ":";
if (!unique.Contains(part))
{
unique.Add(part);
output += part;
}
}
output = output.Substring(1);
return output;
}
ofcourse i've not checked for null input, but i'm sure u'll do it ;)

Categories