I have a .ini file
the .ini:
;app ...
[MSGS]
title#0 = first title..
message#0 = first message
title#1 = second title
message#1 = second message
title#2 = third title
message#2 = third message
I'm using the Nini lib for parsing. I need read it to a dictionary.
I tried this:
public Dictionary<string, string> Read()
{
try
{
Dictionary<string, string> result = new Dictionary<string, string>();
IConfigSource src = config;
IConfig values = src.Configs["MSGS"];
string[] keys = values.GetKeys();
for (int count = keys.Length / 2,i = 0, j = 1;
i < count; i++,
j = i + 1)
{
string titleKey = keys[i];
string messageKey = keys[j];
string titleVal = values.Get(titleKey);
string messageVal = values.Get(messageKey);
result.Add(titleVal, messageVal);
}
}
catch (Exception)
{
}
return null;
}
The output is:
first title.. : first message
first message : second title
second title : second message
I want:
first title.. : first message
second title : second message
third title : third message
How I do this?
Thanks in advance. :)
for (int i = 0; i < keys.Length; i += 2)
{
string titleKey = keys[i];
string messageKey = keys[i+1];
string titleVal = values.Get(titleKey);
string messageVal = values.Get(messageKey);
result.Add(titleVal, messageVal);
}
There are too many variables in your loop - the j and count are not needed and only serve to confuse matters:
for (i = 0; i < keys.Length; i += 2)
{
string titleKey = keys[i];
string messageKey = keys[i + 1];
string titleVal = values.Get(titleKey);
string messageVal = values.Get(messageKey);
result.Add(titleVal, messageVal);
}
Related
I was wondering whether there's a way in a "for" loop to assign a value to a string variable named according to its index number?
let's say I have 3 string variables called:
string message1 = null;
string message2 = null;
string message3 = null;
And I want the 'for' loop to do the something like the following code:
for (int i = 1; i <=3; i++)
{
messagei = "blabla" + i.ToString();
}
I don't want to use an "if" or a "switch" because it will make the code harder to follow.
Is there a way to do that?
You don't want 3 variables with the same name, you want an array of those variables.
string[] messages = new string[3]; // 3 item array
You can then store your items in the array elements
messages[0] = "Apple"; // array index starts at 0!
messages[1] = "Banana";
messages[2] = "Cherry";
Another way to create that array is an inline array initializer, saves some code
string[] messages = { "Apple", "Banana", "Cherry" };
(Note: there are more valid syntaxes for array initialization. Research on the various other methods is left as an exercise.)
And access them via a loop (foreach)
foreach (string fruit in messages)
{
Console.WriteLine("I'm eating a " + fruit);
}
Or for
for (int i = 0; i < messages.Length; i++)
{
Console.WriteLine("I'm eating a " + messages[i]); // reading the value
messages[i] = "blabla" + i.ToString(); // writing a value to the array
}
can you use an array? or list type?
string[] messages = new string[3];
for (int i = 1; i <=3; i++)
{
messages[i] = "blabla" + i.ToString();
}
You said you don't want to have a switch statement. I realize this does have a switch, but if you must have three different variables, you could encapsulate your switch inside a function call:
string message1 = null;
string message2 = null;
string message3 = null;
void SetMessage(int i, string value)
{
if(i == 1)
message1 = value;
etc
}
for (int i = 1; i <=3; i++)
{
SetMessage(i, "blabla" + i.ToString());
}
Not an optimal solution but if you MUST have separate variables it will hide the mess.
You can't do that (well, not sanely). Have you considered using an array of strings instead?
I think you should use an array for this kind of variables.
string[] message = new string[3];
for (int i = 1; i <=3; i++)
{
message[i] = "blabla" + i.ToString();
}
Usually instead of having N differents variables named 1, 2, ..., N the way is to store them in an array:
string message[3];
message[0] = null;
message[1] = null;
message[2] = null;
and then the loop:
for (int i = 0; i <=2; i++)
{
message[i] = "blabla" + i.ToString();
}
Note that, usually again, a set of indexed variables starts with value 0 ;)
I would go about it a little differently, maybe use a dictionary and store your messages. Something like this:
Dictionary<string, string> messages = new Dictionary<string, string>();
for(int i = 1; i <= 3; i++)
{
messages.Add("message" + i.ToString(), i.ToString());
}
You can also do it without the index:
string[] Messages = { "Tom", "Dick", "Harry" };
foreach (String Message in Messages)
{
Response.Write("Hello " + Message + "<br />");
}
If you declare your variable in a class as public variables, you can access them as follow;
public partial class _Default : System.Web.UI.Page
{
public string message1 = null;
public string message2 = null;
public string message3 = null;
public void setVars()
{
for (int i = 1; i <=3; i++)
{
this.GetType().GetField("message" + i.ToString()).SetValue(this, "blabla" + i.ToString());
}
}
}
so I wrote some C# code and I am trying to test it incrementally, do to something that would take a while to explain, but bottom line, I'm new to c# and not understanding the online compiler error messages. Here is the error message I get when I try and compile, but the strings look good to me.
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
string[] solutionSetArray = new string[12];
string ret = "";
string delimeter = "|";
int tempPos = 0;
int counter = 0;
int successFlag = 0;
int patternLength = 5;
for (int index = 0; index < solutionSet.Length; index++)
{
if (solutionSet[index] == delimeter)
{
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
tempPos = index + 1;
counter++;
}
if (solutionSet.Length - index == 1)
{
solutionSetArray[solutionSetArray.Length-1] = solutionSet.Substring(tempPos, solutionSet.Length);
}
}
for (int i = 0; i < patternLength; i++)
{
Random rnd = new Random();
int randIndex = rnd.Next(solutionSetArray.Length);
if (i != patternLength - 1)
{
ret += solutionSetArray[randIndex] + "|";
successFlag++;
}
else
{
ret += solutionSetArray[randIndex];
}
}
if (successFlag == patternLength - 1)
{
Console.WriteLine(ret);
}
else
{
Console.WriteLine("ERROR");
}
The error (which, according to the message, is on line 1, column 11) is being caused by your very first line of code, which begins string.
I can't tell the context from just your post, but my guess is that you are declaring solutionSet in a block that is not inside of a class or function. You should enclose your code in a class or method, e.g.
public class MyClass
{
static public void Main()
{
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
//Rest of code goes here
}
}
By the way, if you're trying to convert solutionSet to an array, you can just write
var solutionSetArray = solutionSet.Split("|");
the problem with your code is
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
after 6 iterations tempPos=34 and index=37 which is running out of bounds of solutionSet. I would suggest to use var solutionSetArray = solutionSet.Split("|"); and also use LinqPad which can be easy for you to debug if possible,.
I can't permanently replace the array members. When I change the value of String Clue, the string being displayed only displays the current value of clue. I think the problem us on the initialization of char[]. I tried to put them in other parts of the code but it produces error. Beginner here! Hope you can help me. Thanks! :)
private void clues(String clue)
{
int idx = numb[wordOn]+4;
char[] GuessHide = Words[idx].ToUpper().ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] != Convert.ToChar(clue.ToUpper()))
GuessHide[a] = '*';
else
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
Guess(string.Join("", GuessHide));
}
Edited - because you initalize GuessHide at each call of calls in your code and you do not store its current state you basically reset it each time. Still, you can make some small changes in your code like this:
private static void clues(string clue, char[] GuessHide, char[] GuessShow)
{
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] == Convert.ToChar(clue.ToUpper()))
{
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
}
Console.WriteLine(string.Join("", GuessHide));
}
Call it like this:
clues("p", GuessHide, GuessShow);
clues("a", GuessHide, GuessShow);
Initialise GuessShow and GuessHide in the outside code like this:
char[] GuessHide = new string('*', Words[idx].Length).ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
public class Program
{
static string[] Words;
static string[] HiddenWords;
public static void Main()
{
Words = new string[] { "Apple", "Banana" };
HiddenWords = new string[Words.Length];
for (int i = 0; i < Words.Length; i++)
{
HiddenWords[i] = new string('*', Words[i].Length);
}
Guess('P', 0);
Guess('a', 0);
Guess('A', 1);
Guess('N', 1);
Console.ReadLine();
}
private static void Guess(char clue, int idx)
{
string originalWord = Words[idx];
string upperedWord = Words[idx].ToUpper();
char[] foundSoFar = HiddenWords[idx].ToCharArray();
clue = char.ToUpper(clue);
for (int i = 0; i < upperedWord.Length; i++)
{
if (upperedWord[i] == clue)
{
foundSoFar[i] = originalWord[i];
}
}
HiddenWords[idx] = new string(foundSoFar);
Console.WriteLine(HiddenWords[idx]);
}
}
Dear stackoverflow members,
I have this string:
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
I want to search for the values where the "keyword" is Position. In this case I want to get back 1 and 2. Each value is "indexed" with its own "keyword". So the value 1 in this string has the Position seperator. The value 1234 has the Article seperator and the value 4321 has the Quantity seperator.
I need a way to search through the string and want to get all positions, articles and quantitys back. Without the keywords.
Output shout be:
string[] position = {"1", "2"};
string[] article = {"1234", "4323"};
string[] quantity = {"4321", "3323"};
Hopefully some can help me here.
Thanks!
This is q quick solution I've come up with in LinqPad:
void Main()
{
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
var Articles = Indices(data, "Article").Dump("Articles: ");
var Posistions = Indices(data, "Position").Dump("Positions :");
var Quantities = Indices(data, "Quantity").Dump("Quantities :");
}
// Define other methods and classes here
public List<int> Indices(string source, string keyword)
{
var results = new List<int>();
//source: http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number
var temp = Regex.Split(source, "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)").ToList().Where (r => !String.IsNullOrEmpty(r)).ToList();
//select the list with index only where key word matches
var indices = temp.Select ((v,i) => new {index = i, value = v})
.Where (t => t.value == keyword);
foreach (var element in indices)
{
int val;
//get previous list entry based on index and parse it
if(Int32.TryParse(temp[element.index -1], out val))
{
results.Add(val);
}
}
return results;
}
Output:
Here's a possible algorithm:
Run trough the list and take each number / keyword.
Put them in a dictionary with key "keyword", value a list with all "numbers".
Iterate the dictionary and print they key + its values.
Below snippet can use to get the output like what you expected.
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
bool isDigit = false;
bool isChar = false;
Dictionary<int, string> dic = new Dictionary<int, string>();
int index = 0;
for (int i = 0; i < data.Length; i++)
{
if (char.IsNumber(data[i]))
{
isDigit = true;
if (isChar)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
index++;
isChar = false;
sb.Remove(0, sb.Length);
sbWord.Remove(0, sbWord.Length);
}
}
else
{
isDigit = false;
isChar = true;
sbWord.Append(data[i]);
}
if (isDigit)
sb.Append(data[i]);
if (i == data.Length - 1)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
}
}
List<string> Position = new List<string>();
List<string> Article = new List<string>();
List<string> Quantity = new List<string>();
if (dic.Count > 0)
{
for (int i = 0; i < dic.Count; i++)
{
if (dic[i].Split('|')[1] == "Position")
Position.Add(dic[i].Split('|')[0]);
else if (dic[i].Split('|')[1] == "Article")
Article.Add(dic[i].Split('|')[0]);
else
Quantity.Add(dic[i].Split('|')[0]);
}
}
string[] Position_array = Position.ToArray();
string[] Article_array = Article.ToArray();
string[] Quantity_array = Quantity.ToArray();
Try this simple solution.
class StrSplit{
public static void main(String args[]){
int i;
String str = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
String pattern= "(?<=Position)|(?<=Article)|(?<=Quantity)";
String[] parts = str.split(pattern);
List<String> Position = new ArrayList<String>();
List<String> Article = new ArrayList<String>();
List<String> Quantity = new ArrayList<String>();
for( i=0;i<parts.length;i++)
{
pattern="Position";
String[] subParts;
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Position.add(subParts[0]);
}
pattern="Article";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Article.add(subParts[0]);
}
pattern="Quantity";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Quantity.add(subParts[0]);
}
}
System.out.println("Position:");
for(i = 0; i < Position.size(); i++) {
System.out.println(Position.get(i));
}
System.out.println("Article:");
for(i = 0; i < Article.size(); i++) {
System.out.println(Article.get(i));
}
System.out.println("Quantity:");
for(i = 0; i < Quantity.size(); i++) {
System.out.println(Quantity.get(i));
}
}
}
Output:
Position:
1
2
Article:
1234
4323
Quantity:
4321
3323
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 8 years ago.
Improve this question
I have a situation where my string can't go past a certain point, so what I want to do is cut it into smaller strings of "x" characters, and then print them one by one on top of each other. They don't all need to be equal, if x is 5, and I have an 11 character string, printing 3 lines with 5, 5, and 1 characters is fine. Is there an easy way to do this in C#?
Example:
string Test = "This is a test string";
stringarray = Cutup(Test, 5);
//Result:
//"This "
//"is a "
//"test "
//"strin"
//"g"
try something like this:
public string[] Cutcup(string s, int l)
{
List<string> result = new List<string>();
for (int i = 0; i < s.Length; i += l)
{
result.Add(s.Substring(i, Math.Min(5, s.Substring(i).Length)));
}
return result.ToArray();
}
You could cut up the strings then do a test.lastIndexOf(' '); If that helps
You can use the String Manipultion function Substring() and a for loop to accomplish this.
here is an example
int maxChars = 5;
String myStr = "This is some text used in testing this method of splitting a string and just a few more chars and the string is complete";
List<String> mySubStrings = new List<String>();
while (myStr.Length > maxChars)
{
mySubStrings.Add(myStr.Substring(0,maxChars));
myStr = myStr.Substring(maxChars);
}
mySubStrings.ToArray();
List<string> result = new List<string>();
string testString = "This is a test string";
string chunkBuilder = "";
int chunkSize = 5;
for (int i = 0; i <= testString.Length-1; i++)
{
chunkBuilder += testString[i];
if (chunkBuilder.Length == chunkSize || i == testString.Length - 1)
{
result.Add(chunkBuilder);
chunkBuilder = "";
}
}
Another try, with less string concatenations
string Test = "This is a test string";
List<string> parts = new List<string>();
int i = 0;
do
{
parts.Add(Test.Substring(i,System.Math.Min(5, Test.Substring(i).Length)));
i+= 5;
} while (i < Test.Length);
Here are a couple more ways. Cutup2 below is more efficient but less pretty. Both pass the test case given.
private static IEnumerable<string> Cutup(string given, int chunkSize)
{
var skip = 0;
var iterations = 0;
while (iterations * chunkSize < given.Length)
{
iterations++;
yield return new string(given.Skip(skip).Take(chunkSize).ToArray());
skip += chunkSize;
}
}
private static unsafe IEnumerable<string> Cutup2(string given, int chunkSize)
{
var pieces = new List<string>();
var consumed = 0;
while (consumed < given.Length)
{
fixed (char* g = given)
{
var toTake = consumed + chunkSize > given.Length
? given.Length - consumed
: chunkSize;
pieces.Add(new string(g, consumed, toTake));
}
consumed += chunkSize;
}
return pieces;
}
All in one line
var size = 5;
var results = Enumerable.Range(0, (int)Math.Ceiling(test.Length / (double)size))
.Select(i => test.Substring(i * size, Math.Min(size, test.Length - i * size)));
I once made an extensionmethod that can be used for this:
public static IEnumerable<IEnumerable<T>> Subsequencise<T>(this IEnumerable<T> input, int subsequenceLength)
{
var enumerator = input.GetEnumerator();
SubsequenciseParameter parameter = new SubsequenciseParameter { Next = enumerator.MoveNext() };
while (parameter.Next)
yield return getSubSequence(enumerator, subsequenceLength, parameter);
}
private static IEnumerable<T> getSubSequence<T>(IEnumerator<T> enumerator, int subsequenceLength, SubsequenciseParameter parameter)
{
do
{
yield return enumerator.Current;
} while ((parameter.Next = enumerator.MoveNext()) && --subsequenceLength > 0);
}
// Needed to let the Subsequencisemethod know when to stop, since you cant use out or ref parameters in an yield-return method.
class SubsequenciseParameter
{
public bool Next { get; set; }
}
then you can do this:
string Test = "This is a test string";
stringarray = Test.Subsequencise(5).Select(subsequence => new String(subsequence.Toarray())).Toarray();
Here's a rather LINQy one-liner:
static IEnumerable<string> SliceAndDice1( string s , int n )
{
if ( s == null ) throw new ArgumentNullException("s");
if ( n < 1 ) throw new ArgumentOutOfRangeException("n");
int i = 0 ;
return s.GroupBy( c => i++ / n ).Select( g => g.Aggregate(new StringBuilder() , (sb,c)=>sb.Append(c)).ToString() ) ;
}
If that gives you a headache, try the more straightforward
static IEnumerable<string> SliceAndDice2( string s , int n )
{
if ( s == null ) throw new ArgumentNullException("s") ;
if ( n < 1 ) throw new ArgumentOutOfRangeException("n") ;
int i = 0 ;
for ( i = 0 ; i < s.Length-n ; i+=n )
{
yield return s.Substring(i,n) ;
}
yield return s.Substring(i) ;
}