Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a function with takes something like a SSN number as argument. The input can be in one of the following formats (validity of SSN is not a factor)
999-99-9999
99-999-9999
9-9999-9999
999999999
99999999-9
Hyphen can be at any location and input can be of any length.
This method will create a random number with same length of input and the output will have hyphens on same locations as input
for example, if input 9-9999-9999 is passed then random output could be 1-2234-5678 (match hyphen location)
for example, if input 99999999-9 is passed then random output could be 12234567-8 (match hyphen location)
public String GenerateNumber(String input)
{
//find the location of hyphens in the input
String output = Generate random number of same length as input //ToString();
//put hyphens on the random number generated above at the same locations matching input
return output
}
Would be helpful if sample code provided in C# but java would also work.
Here's one way of doing it.
public string GenerateNumber(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
throw new ArgumentNullException("input");
}
Random rand = new Random();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '-')
{
builder.Append("-");
}
else
{
builder.Append(rand.Next(0, 9).ToString());
}
}
return builder.ToString();
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I have a string
"This is a test string for testing in dotnet4.8 (.net)" 53 chars
The requirement is that if the length of the string is greater than 40 characters
then to replace characters with "" starting from the (.net) moving to the left until the total chars is 40 , so i will end up with
"This is a test string for testing (.net)"
and it doesnt matter if the word is cut off , cause there could be scneario where the string is different but they will always end in (.net)
If I understood you right, you want the actual text to be 34 letters long, so when adding your "(.net)" ends up being 40.
so I guess something in the realms of:
public string Shorten(string s)
{
if(s.Length > 40)
return s.Substring(0,34) + "(.net)";
else
return s;
}
Try this:
const int maxLength = 40;
const string suffix = "(.net)";
var text = "This is a test string for testing in dotnet4.8 (.net)";
var exceed = text.Length - maxLength;
if (exceed > 0)
{
text = text.Substring(0, text.Length - exceed - suffix.Length) + suffix;
}
You could do this with Regex:
var input = "This is a test string for testing in dotnet4.8 (.net)";
var match = Regex.Match(input, #"^(.{0,34}).*?\(\.net\)$");
var result = $"{match.Groups[1].Value}(.net)";
That gives This is a test string for testing (.net).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to extract substring from string but starting with the first letter
example :
string s1 = "12 x 13 ABC 12# 15.8" substring = ABC 12# 15.8
string s2 = "25 x 32 FER #23.8" substring = FER #23.8
I tried the index of for the letter A or F but it didn't work
thanks
This should work (in case you use a non-letter character instead of x)
string SubstringThis(string input)
{
return new string(input.SkipWhile(c => !char.IsLetter(c)).ToArray());
}
Simple utility function:
string SubstringFromFirstLetter(string s)
{
for (int i=0; i < s.Length; ++i)
{
if (char.IsLetter(s[i]))
{
return s.Substring(i);
}
}
return "";
}
Keep in mind that x is a letter. Do you want it to match only capitalized letters?
public static string GetSubstringStartingWithFirstAlphaCharacter(this string toEvaluate)
{
const string pattern = "([a-zA-Z])(.+)";
var regex = new Regex(pattern);
return regex.Match(toEvaluate).Value;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have some problems with split and check string.
I need to split string, replace halfs and check is this the same as the second string.
example: first string = tokyo second string = koyto
soo... S = a+b = b+a
S - a = b and S - b = a
a and b is part of one string (S) and may have different long in this case a = to and b = koy
first I need to check string length - is the are different - then write Error - it's easy
the I thought that I can compare strings in ASCII (case sensitivity is not important) and it' could be ok but...
I can create string tooky which have got the same size in ASCII but is not created from split and invert parts of first string...
any ideas?
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
split string ?
}
else
Console.WriteLine("This two words are different. No result found.");
Console.Read();
}
I would suggest doing the comparisons with strings. You can use the String.ToLower() method to convert them both to lowercase for comparison.
I am not exactly sure what problem you are trying to solve is, but from what I understand you are trying to check if string S can be split into two substrings that can be rearranged to make string T.
To check this you will want something similar to the following
for (int i = 0; i < S.length; i++) {
string back = S.substring(i);
string front = S.substring(0,i);
if (T.equals(back + front))
result = true;
}
Hope this helps
If you want to compare equality of two collections you should consider using LINQ:
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
if (S.Intersect(T).Any())
{
Console.WriteLine("The Contents are the same");
Console.Read();
}
}
else
Console.WriteLine("This two words are diferent. No result found.");
Console.Read();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a string which has a following format:
"####/xxxxx"
The text before the "/" is always an integer and I need to read it. How do I get only the integer part of this string (before the "/")?
Thank you for your help.
You can split the string on / and then use int.TryParse on the first element of array to see if it is an integer like:
string str = "1234/xxxxx";
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
int number = 0;
if (str.Length == 2 && int.TryParse(array[0], out number))
{
//parsing successful.
}
else
{
//invalid number / string
}
Console.WriteLine(number);
Use IndexOf and Substring:
int indexOfSlash = text.IndexOf('/');
string beforeSlash = null;
int numBeforeSlash = int.MinValue;
if(indexOfSlash >= 0)
{
beforeSlash = text.Substring(0, indexOfSlash);
if(int.TryParse(beforeSlash, out numBeforeSlash))
{
// numBeforeSlash contains the real number
}
}
Another alternative: use a regular expression:
var re = new System.Text.RegularExpression(#"^(\d+)/", RegexOptions.Compiled);
// ideally make re a static member so it only has to be compiled once
var m = re.Match(text);
if (m.IsMatch) {
var beforeSlash = Integer.Parse(re.Groups[0].Value);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
How can I move all words of seven letters or more in one string to another?
I know that I need a foreach loop to go through each character, and some sort of way of seeing whether the next character is blank while using a counter; then, if the next char is blank, see whether the counter is greater than or equal to seven, then move what was just there to a new string, then into a file.
You can use LINQ's Where method:
string strBigText = Console.ReadLine();
IEnumerable<string> words = strBigText.Split(" ").Where(o => o.Length >= 7);
This is going to split your text at every space, creating an array of strings, then retrieve only the elements (strings) that have a length greater than or equal to 7.
You could use string.split
string[] array = yourString.split(' ');
list<string> longStrings = new list<string>();
for(int i = 0; i < array.length; i++){
if(array[i].length >= 7){
longStrings.add(array[i]);
}
}
Something like that.
I would recommend RegExp for this (http://www.regular-expressions.info/).
At the top of your code, say:
using System.Text.RegularExpressions;
Then, in your routine, just go:
string input = textbox1.Text; // or wherever else you get your string from
MatchCollection matches = new Regex(#"(^|\b)\w{7}\w*(\b|$)").Matches(input);
string[] results = new string[matches.Count];
for (int i = 0; i != matches.Count; i++)
results[i] = matches[i];
//Now results will be an array of the 7-letter words.