I'm trying to take a string and split it. However, whenever I use fullName.Split Visual Studio says System.Array does not contain a definition for Split.
This is my main method so far.
public static void Main(string[] args)
{
string inValue;
int noNames;
string[] names = new string[100];
// find number of names
Console.WriteLine("Enter the number of names: ");
inValue = Console.ReadLine();
int.TryParse(inValue, out noNames);
string[] fullName = new string[noNames];
for (int i = 0; i < fullName.Length; i++)
{
string[] name = fullName.Split(' '); //error appears here
}
}
What's strange is that I was able to write another program shortly before this that uses the Split method. That program had no issues. I'm not sure if there is something wrong with my code, or an error with Visual Studio. Can anyone assist me in solving this error? The program isn't complete, if that matters.
You need to call it on the element of the array, not the array itself.. So it would be:
string[] name = fullName[i].Split(' ');
You are trying to split an array, not a string. Arrays cannot be split this way using a certain character like strings
try this
public static void Main(string[] args)
{
string inValue;
int noNames;
string[] names = new string[100];
// find number of names
Console.WriteLine("Enter the number of names: ");
inValue = Console.ReadLine();
int.TryParse(inValue, out noNames);
string[] fullName = new string[noNames];
for (int i = 0; i < fullName.Length; i++)
{
string[] name = fullName[i].Split(' '); //error appears here
}
}
Related
I am trying to compare two string in C# and get the differences between them i.e words which are not present in the other string ignoring cases and commas just focusing on the words. If one string contains two or multiple the and the second string has one the, it means this will be disregarded as it exists in both. Example I have two strings like below;
Cat meet's a dog
Cat meet's a dog and a bird
The difference between those two strings is and bird because it does not exist in the first one or vise versa and I want to get those two words and bird either in a List or a new string with spaces between them and in other words I want the words which are not present in the other string. Is there a way this can be done in C#?
Here's a way using LINQ. You don't need the "ToList()" part, but you mentioned that as one form of output you'd want:
string str1 = "Cat meet's a dog";
string str2 = "Cat meet's a dog and a bird";
string[] str1Words = str1.ToLower().Split(' ');
string[] str2Words = str2.ToLower().Split(' ');
var uniqueWords = str2Words.Except(str1Words).Concat(str1Words.Except(str2Words)).ToList();
// Do whatever you want with uniqueWords instead
Console.WriteLine($"output: {String.Join(" ", uniqueWords)}");
#ngdeveloper. This is my variant of your solution (had to post it in a separate answer because of the length):
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int shortestLenght;
int longestLenght;
bool firstIsLongest;
if (_firstStringArray.Length > _secondStringArray.Length)
{
firstIsLongest = true;
shortestLenght = _secondStringArray.Length;
longestLenght = _firstStringArray.Length;
}
else
{
firstIsLongest = false;
shortestLenght = _firstStringArray.Length;
longestLenght = _secondStringArray.Length;
}
for (int i = 0; i < shortestLenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = shortestLenght; i < longestLenght; i++)
{
if (firstIsLongest)
_stringsDiff._diffList1.Add(_firstStringArray[i]);
else
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
return _stringsDiff;
}
I wrote you a simple solution, hope it will help -
The main method is called 'Difference' it receive 2 strings to compare and return an object called StringDiff.
It runs 2 loops, first comparing between the two strings char by char and then adding the rest of the longer string.
The 'StringDiff' object is a class with 2 char lists that represnt the differences of each string.
In the main method i use String.join to convert the char lists to a string and print it.
internal class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("enter first string");
string firstString = Console.ReadLine();
Console.WriteLine("enter second string");
string secondString = Console.ReadLine();
StringsDiff _stringsDiff = Difference(firstString, secondString);
Console.WriteLine(
$"fist string difference: {string.Join("", _stringsDiff._diffList1)} / second string difference: {string.Join("", _stringsDiff._diffList2)}");
Console.WriteLine("/////////////////////////////////////");
}
}
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int lenght;
if (_firstStringArray.Length > _secondStringArray.Length)
{
lenght = _secondStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _secondStringArray.Length; i < _firstStringArray.Length; i++)
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
}
}
else
{
lenght = _firstStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _firstStringArray.Length; i < _secondStringArray.Length; i++)
{
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
return _stringsDiff;
}
class StringsDiff
{
public List<char> _diffList1 = new List<char>();
public List<char> _diffList2 = new List<char>();
}
}
Remember to use "string.join" to connect the lists objects if you need a string.
I have a problem in my code and I have no idea how to fix it. I need to copy every letter of the user entered word to array, but there is an error "Index was outside the bounds of the array". I know that thir error means that I don't have correct size of the array, but I am using ReadLine and I can't enter static size. It can be changed due user entered text.
Code:
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[] { };
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You should define length of str
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[text.Length];//<-- NOTE THIS
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You can use Linq to make this a one-liner:
using System.Linq;
// ...
// ...
var separateLettersAsList = text.ToList();
var separateLettersAsArray = text.ToArray();
I'm struggling to find a way to first
Get User input to decide how many elements will be in the next string array
Then to convert the Users input from string to int for the array
Is there also a way to display the element number along with the string element like so.... Console.WriteLine(1. StringName 2.StringName);
This is my code :
Console.WriteLine("How many countries you want mate ? ");
string numberOfCountries = Console.ReadLine();
Console.WriteLine("Please name your countries ");
string[] nameOfCountries = new string[10];
for (int i = 0; i < nameOfCountries.Length ; i++)
{
nameOfCountries[i] = Console.ReadLine();
}
Get User input to decide how many elements will be in the next string array
You can put a variable in when creating an array size, like this:
string[] nameOfCountries = new string[someVariable];
someVariable needs to be an int. Console.WriteLine returns a string, so you need to parse the string to an int. You can use int.Parse for that. So:
int numberOfCountries = int.Parse(Console.ReadLine());
string[] nameOfCountries = new string[numberOfCountries];
Note that Parse will throw an exception if it isn't able to correctly parse the input in to an integer.
Is there also a way to display the element number along with the string element
You can use a similar loop like you are when you are assigning values to the array.
Console.WriteLine("{0}: {1}", i, nameOfCountries[i]);
Program:
string mate = "mate";
Console.WriteLine($"How many countries you want {mate}?");
string numberOfCountries = Console.ReadLine();
int numberOfCountriesInt;
while ( !int.TryParse( numberOfCountries, out numberOfCountriesInt ) )
{
mate = mate.Insert(1, "a");
Console.WriteLine($"How many countries you want {mate}?");
numberOfCountries = Console.ReadLine();
}
Console.WriteLine("Please name your countries ");
string[] namesOfCountries = new string[numberOfCountriesInt];
for (int i = 0; i < namesOfCountries.Length; i++)
{
namesOfCountries[i] = Console.ReadLine();
}
for (int i = 0; i < namesOfCountries.Length; i++)
{
Console.WriteLine($"{i+1}, {namesOfCountries[i]}");
}
Output:
How many countries you want mate?
Two
How many countries you want maate?
Two?
How many countries you want maaate?
2
Please name your countries
Stralya
PNG
1. Stralya
2. PNG
Please note that a List<string> may be better to store data like this. Then you can do something like this:
Console.WriteLine("Please name your countries ");
var namesOfCountries = new List<string>();
for (int i = 0; i < numberOfCountriesInt; i++)
{
namesOfCountries.Add(Console.ReadLine());
}
My front-end application sends strings that look like this:
"12-15"
to a back-end C# application.
Can someone give me some pointers as to how I could extract the two numbers into two variables. Note the format is always the same with two numbers and a hyphen between them.
string stringToSplit = "12-15";
string[] splitStringArray;
splitStringArray = stringToSplit.Split('-');
splitStringArray[0] will be 12
splitStringArray[1] will be 15
Split the string into parts:
string s = "12-15";
string[] num = s.Split('-');
int part1 = Convert.ToInt32(num[0]);
int part2 = Convert.ToInt32(num[1]);
int[] numbers = "12-15".Split('-')
.Select(x => {
int n;
int.TryParse(x, out n);
return n;
})
.ToArray();
We call Split on a string instance. This program splits on a single character
string s ="12-15";
string[] words = s.Split('-');
foreach (string word in words)
{
int convertedvalue = Convert.ToInt32(word );
Console.WriteLine(word);
}
string[] ss= s.Split('-');
int x = Convert.ToInt32(ss[0]);
int y = Convert.ToInt32(ss[1]);
more info
You can use the below code to split and it will return string for each value, then you can typecast it to any type you wish to ...
string myString = "12-15-18-20-25-60";
string[] splittedStrings = myString.Split('-');
foreach (var splittedString in splittedStrings)
{
Console.WriteLine(splittedString + "\n");
}
Console.ReadLine();
Here is the correct version without the wrong code
string textReceived = "12-15";
string[] numbers = textReceived.Split('-');
List<int> numberCollection = new List<int>();
foreach (var item in numbers)
{
numberCollection.Add(Convert.ToInt32(item));
}
String numberString = "12-15" ;
string[] arr = numberString.Split("-");
Now you will get a string array , you can use parsing to get the numbers alone
int firstNumber = Convert.ToInt32(arr[0]);
Helpful answer related to parsing :
https://stackoverflow.com/a/199484/5395773
You could convert that string explicitly to an integer array using Array.ConvertAll method and access the numbers using their index, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = Array.ConvertAll(number.Split('-'), int.Parse);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
}
}
}
Or you can explicitly convert the numeric string using int.Parse method, the int keyword is an alias name for System.Int32 and it is preffered over the complete system type name System.Int32, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = number.Split('-');
var one = int.Parse(numbers[0]);
var two = int.Parse(numbers[1]);
Console.WriteLine(one);
Console.WriteLine(two);
}
}
}
Additional read: Please check int.Parse vs. Convert.Int32 vs. int.TryParse for more insight on parsing the input to integer
string str = null;
string[] strArr = null;
int count = 0;
str = "12-15";
char[] splitchar = { '-' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
Good afternoon,
I am running a function in C# designed to remove certain "stopwords" from a string such as "the, or, it" so it will be more useful in natural language processing. However the function will for some reason not remove the first instance of the word.
For example
input:
The lion the witch and the wardrobe
return:
the lion witch and wardrobe (I am not using 'and' as a stopword as it can be useful)
My function is below:
private void filterStopWords(string textToFilter)
{
textToFilter.ToLower();
StringBuilder builder = new StringBuilder(textToFilter);
for (int i = 0; i < 27; i++)
{
if (textToFilter.Contains(stopWords[i]))
{
builder.Replace(stopWords[i], " ");
}
}
filterQueryBox.Text = builder.ToString();
}
Stopwords[] is an array containing all my stopwords.
Thanks in advance for any response that may help me here!
My guess would be that your stopword is " the " with leading and trailing blanks. The first occurence of "the" doesn't have a blank in front of it, so it doesn't match.
You almost there..
String.ToLower returns new string instance. You need to assign it to another or same string reference.
StringBuilder.Replace returns new StringBuilder instance. You need to assign it to another or same StringBuilder reference.
And since you first use ToLower than replace the "the", you shouldn't have "the.." part in your instance. Because it matches in your stopWords array item.
static void Main(string[] args)
{
filterStopWords("The lion the witch and the wardrobe");
}
private static void filterStopWords(string textToFilter)
{
var stopWords = new [] {"The", "or", "it"};
textToFilter = textToFilter.ToLower();
StringBuilder builder = new StringBuilder(textToFilter);
for (int i = 0; i < 3; i++)
{
if (textToFilter.Contains(stopWords[i]))
{
builder = builder.Replace(stopWords[i], " ");
}
}
var result = builder.ToString();
Console.WriteLine(result);
}
Result will be;
lion w ch and wardrobe