【问题标题】:I'm trying to insert a string into another string without using built-in functions我试图在不使用内置函数的情况下将一个字符串插入另一个字符串
【发布时间】:2021-12-25 15:45:37
【问题描述】:
class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Your string: ");
            string str = Console.ReadLine();

            
            stringFuncs.Insert(str, "Hello", 5);

            
        }
    }

public static string SubString(string word,int a, int b)
        {

            for(int i = a; i < b; i++)
            {
                Console.Write(word[i]);//my substring method
            }
            return word;
        }
public static string Insert(string word, string subs, int index)
        {
            
            int numberOfLetters = 0;
            foreach (var c in word)
            {
                numberOfLetters++;
            }

            
            Console.WriteLine(stringFuncs.SubString(word, 0, index) + subs + stringFuncs.SubString(word, index,numberOfLetters-index));
            return word;

          

        }

每当我写东西时,我都会得到这个输出:My stringHello My string

我的子字符串方法是错误的,我怎样才能让它只取我需要的部分并将其返回?

【问题讨论】:

  • 什么是AltDizi?您所说的“为什么要再次占用所有字符串”是什么意思?恐怕目前我发现你的问题很难理解。请阅读codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question 并进行适当的编辑。请注意,您的 SubString 方法只是在 printing 部分之后返回原始字符串 - 所以如果您对它返回原始字符串感到惊讶,您应该解释您 expected 去做吧。
  • 你的 stringFuncs 显然是一个你重写了 SubString 和 Insert 方法的类。为什么不让这门课出现在你的帖子中?更重要的是:不要在这些方法中使用 Console.Write 作为输出。这很令人困惑。 Console.WriteLine 可用于程序的主要部分进行测试,但不能用于方法本身的结果。 Insert 方法不需要返回 'word' 字符串,因为您使用 Insert 一次作为 void 方法。
  • 而且你的 a et b 参数都是索引。所以最后一次调用你的 SubString 方法必须考虑到索引小于字母总数的一半。在标准 C# Substring 中,第一个 arg 'a' 使用索引,'b' 使用多个字符。

标签: c# string function


【解决方案1】:

你可以使用我的方法(如果你只需要一个子字符串的方法):

class Program
{
    static string CustomSubstring(string text, short startIndex, short indexInQuestion)
    {
        short i;
        for (i = startIndex; i < text.Length; i++) ;
        StringBuilder Temp = new StringBuilder();
        //"StringBuilder.Append()" is faster than "string+=string"
        //switch is faster than if
        switch (indexInQuestion < i)
        {
            case true:
                char[] C = text.ToArray();
                for (short j = startIndex; j <= indexInQuestion; j++)
                {
                    Temp.Append(C[j]);
                }
                break;
        }
        return Temp.ToString();
    }
    static void Main(string[] args)
    {
        Console.WriteLine(CustomSubstring("Merry Christmas", 6, 14));
        Console.ReadKey();
    }
}

输出:圣诞节

【讨论】:

  • 注意:如果这个解决方案对你有帮助,请标记为答案(不要忘记投票给我)。
【解决方案2】:

如果您想要一个接近您的解决方案,只需进行最少的更改,请考虑以下几点:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main()
        {
            Console.Write("Your string: ");
            string str = Console.ReadLine();                            // Console should be used only in the main part, not the methods
            Console.WriteLine(StringFuncs.Insert(str, "Hello", 5));
            Console.ReadKey();                                          // Waits for the user to press a key
        }
    }

    public class StringFuncs
    {
        /// <summary>
        /// Extracts a part of a string
        /// </summary>
        /// <param name="word"></param> The string you want an extraction from
        /// <param name="startIndex"></param>The position you want tthe extraction to start
        /// <param name="numberOfChars"></param>The number of chars to be extracted
        /// <returns></returns>
        public static string SubString(string word, int startIndex, int numberOfChars)
        {
            string result = "";                         // initialisation of the result string
            for (int i = 0; i < numberOfChars; i++)
            {
                result += word[startIndex + i];         // adding chars one by one 
            }
            return result;                              
        }

        // the method below was detached from your old Insert method as it can be re-used
        /// <summary>
        /// Calculates the number of letter of a string
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public static int NumberOfLetters(string word)
        {
            int numberOfLetters = 0;
            foreach (char c in word)    // be explicite, specific and avoid the "var" thing
            {
                numberOfLetters++;
            }
            return numberOfLetters;
        }

        /// <summary>
        /// Inserts a string into another one, at a given position
        /// </summary>
        /// <param name="targetString"></param>The string which will receive the second one
        /// <param name="insertString"></param>The string to be inserted in the first one
        /// <param name="insertPosition"></param>The position of insertion in the first string
        /// <returns></returns>
        public static string Insert(string targetString, string insertString, int insertPosition)
        {
            return SubString(targetString, 0, insertPosition) + insertString + SubString(targetString, insertPosition, NumberOfLetters(targetString) - insertPosition);
        }
    }
}

这不是专家级处理和速度的争论,而是显示了一种更具教学性的方法,您可以在其他项目中复制。我只是更喜欢可读性和理解力。

【讨论】:

    猜你喜欢
    • 2015-02-11
    • 2012-09-25
    • 2011-05-20
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多