Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm stack with a task which ask for "read from console" (C#) a text (string) and get words separated by spaces.
for example: phrase=**"i love this world love"** BUT I need to try this WITHOUT methods or functions like SPLIT or REGEX or similar.
I need to compare 2 words and I dont know how to catch 'em in separated word1 word2 fullphrase.
What i want is word1="this" word2= "world" AND CHECK if there are 2 words REPEATED
string frase, palabra1="",pal2="";
bool si = false;
Console.WriteLine("Entra frase");
frase = Console.ReadLine();
int j = 0;
for (int i = 0; i < frase.Length; i++)
{
if (frase[i] != ' ')
{
palabra1 += frase[i];
if (pal2 == palabra1) si = true;
}
else
{
pal2 = palabra1;
palabra1 = "";
}
}
if (si == true) Console.WriteLine($" SI HAY palabras seguidamente
repetidas ");
else Console.WriteLine($"NO HAY PALABRAS REPETIDAS AQUI");
If you can't use any functions(split, regex, indexOf, etc), then what you should do is loop through each character of the text, and push the currently processed segment into your word list when you reach a (white)space.
String testString = "This is a test string ";
ArrayList words = new ArrayList();
string currentWord = "";
foreach(char c in testString)
{
if(Char.IsWhiteSpace(c))
{
if(currentWord.Length > 0)
{
words.Add(currentWord);
currentWord = "";
}
}
else
{
currentWord+=c;
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
public static string TrimLeft(string word)
{
int numberOfLetters = 0;
foreach (var c in word)
{
numberOfLetters++;
}
int start = 0, end = numberOfLetters - 1;
string b = "";
for (int i = 0; i < numberOfLetters; i++)
{
if (!char.IsWhiteSpace(word[i]))
{
start = i;
b += word[i];
}
}
Console.WriteLine("Trimmed version: {0}", b);
return word;
}
i'm trying to write trimleft function by myself i couldnt quite figure out how i did the normal trim version but how can i do the trimleft version of it without using any inbuilt string. functions like substring etc.
this is a shorter version, it was tested and working properly
public static string TrimLeft(string word)
{
string result = "";
bool trimDone = false;
foreach (var chr in word)
{
if (chr == ' ' && !trimDone) continue;
result = result + chr;
trimDone = true;
}
Console.WriteLine("Trimmed version: {0}", result);
return result;
}
test
var word = " abc def !";
word = TrimLeft(word);
result
abc def !
Somebody could suggest a string builder, but as I understand it is out of the scope of the project
also there is another version but I think that it is out of the scope too
public static string TrimLeft(string word)
{
var i = 0;
foreach (var chr in word)
{
if (chr != ' ')
{
if ( i > 0)
{
Console.WriteLine($"Trimmed version:{word[i..]}");
return word[i..];
}
else break;
}
i++;
}
Console.WriteLine($"Nothing To Trim : {word}");
return word;
}
Find the index of the first non-space character in your input string, then copy the rest to your result string and return it.
The first non-space char can be found with a loop and the copy operation can also be done with a loop, if IndexOf or Substring are not allowed when solving this problem. A string builder could be used to efficiently build your result string.
Another way to do it is:
public static string TrimLeft(string word)
{
int i = 1;
foreach (var chr in word)
{
if (chr != ' ') break;
i++;
}
i--;
return word[i..];
}
see: Fiddle
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to pick class names of all classes from given input code. However my code is picking just one class name. What should I do?
I am working on a Windows form in C#. I have tried to it do with a foreach loop but it is not working
private void btnDetect_Click(object sender, EventArgs e)
{
// splitting code
string mystr = richTextBox1.Text;
if (mystr.ToLower().Contains("class"))
{
string[] splitText = mystr.Split(new char[] { ' ' });
foreach (string word in splitText)
{
int classindex = Array.FindIndex(splitText, r => r.Contains("class"));
string className = splitText[classindex + 1];
MessageBox.Show(className);
}
}
else
MessageBox.Show("class not found");
}
}
I expect the output to show all the class names in the input, but the output I get is only the first class name
Array.FindIndex always returns the first index because the condition never changes.
You could use:
string[] tokens = mystr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
List<string> classList = new List<string>();
for (int i = 0; i < tokens.Length - 1; i++)
{
if (tokens[i].Equals("class", StringComparison.InvariantCultureIgnoreCase))
classList.Add(tokens[++i]);
}
you could use this method :
public IEnumerable<string> GetClasses(string str)
{
if (!str.Contains("Class", StringComparison.OrdinalIgnoreCase)) yield break;
string[] words =str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int wordsCount = words.Length;
for (var index = 0; index < wordsCount; index++)
{
string word = words[index];
if (!word.Equals("Class", StringComparison.OrdinalIgnoreCase)) continue;
if (wordsCount > index + 1) continue;
if (words[index + 1].Equals("Class", StringComparison.OrdinalIgnoreCase)) continue;
yield return words[index + 1];
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
What I need is to get the common part between two words and get the differences too.
Examples:
Scenario 1
word1 = Testimonial
word2 = Test
Will return
Common part Test, difference imonial
Scenario 2
word1 = Test
word2 = Testimonial
Will return
Common part Test, difference imonial
Scenario 3
word1 = Testimonial
word2 = Tesla
Will return
Common part Tes, difference timonial and la
The common part of both words are always on the beginning.
In other words, I need to preserve the begin of the word until the words get different, than I need to get the differences.
I'm trying to do that avoid using a lot of if's and for's.
Thank you guys.
LINQ alternative:
string word1 = "Testimonial", word2 = "Tesla";
string common = string.Concat(word1.TakeWhile((c, i) => c == word2[i]));
string[] difference = { word1.Substring(common.Length), word2.Substring(common.Length) };
class Program
{
static void Main(string[] args)
{
string word1 = "Testimonial";
string word2 = "Tesla";
string common = null;
string difference1 = null;
string difference2 = null;
int index = 0;
bool same = true;
do
{
if (word1[index] == word2[index])
{
common += word1[index];
++index;
}
else
{
same = false;
}
} while (same && index < word1.Length && index < word2.Length);
for (int i = index; i < word1.Length; i++)
{
difference1 += word1[i];
}
for (int i = index; i < word2.Length; i++)
{
difference2 += word2[i];
}
Console.WriteLine(common);
Console.WriteLine(difference1);
Console.WriteLine(difference2);
Console.ReadLine();
}
}
You can use Intersect and Except to get it:
static void Main(string[] args)
{
var string1 = "Testmonial";
var string2 = "Test";
var intersect = string1.Intersect(string2);
var except = string1.Except(string2);
Console.WriteLine("Intersect");
foreach (var r in intersect)
{
Console.Write($"{r} ");
}
Console.WriteLine("Except");
foreach (var r in except)
{
Console.Write($"{r} ");
}
Console.ReadKey();
}
Note that this is a simple solution. For example:
Except would not work if you change the order of the strings, like :
"Test".Except("Testmonial");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to replace a comma in a string.
For example, the data is the currency value of a part.
Eg. 453,27 This is the value I get from an SAP database
I need to replace the comma to a period to fix the value to the correct amount. Now sometimes, it will be in the thousands.
Eg. 2,356,34 This value needs to be 2,356.34
So, I need help manipulating the string to replace comma that is 2 characters from the end.
Thanks for the help
string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
You'll need to add a bit of checking for cases where there are no commas in the string, etc. but that's the core code.
You could also do it with a regex, but this is simple and reasonably efficient.
A quick google search gave me this:
void replaceCharWithChar(ref string text, int index, char charToUse)
{
char[] tmpBuffer = text.ToCharArray();
buffer[index] = charToUse;
text = new string(tmpBuffer);
}
So your "charToUse" should be '.'. If it always is 2 characters from end, your index should be
text.length - 3.
http://www.dreamincode.net/code/snippet1843.htm
If I understand correctly, you always need to replace the last comma with a period.
public string FixSAPNumber(string number)
{
var str = new StringBuilder(number);
str[number.LastIndexOf(',')] = '.';
return str.ToString();
}
string item_to_replace = "234,45";
var item = decimal.Parse(item_to_replace);
var new_item = item/100;
//if you need new_item as string
//then new_item.ToString(Format)
Use this :
string str = "2,356,34";
string[] newStr = str.Split(',');
str = string.Empty;
for (int i = 0; i <= newStr.Length-1; i++)
{
if (i == newStr.Length-1)
{
str += "."+newStr[i].ToString();
}
else if (i == 0)
{
str += newStr[i].ToString();
}
else
{
str += "," + newStr[i].ToString();
}
}
string s = str;
string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
x = x.Remove(x.Length - 3, 1);
x = x.Insert(x.Length - 2, ".");
}