the usage of String.trim()

使用java.lang.String.trim()方法去除字符串前后空格

下面的示例演示使用的java.lang.String.trim()方法

package com.yiibai;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    // string with leading and trailing white space
    String str = " This is YiiBai ";
    
    System.out.print("Before trim = ");
    System.out.println(".." + str + "..");
    
    // leading and trailing white space removed
    System.out.print("After trim = ");
    System.out.println(".." + str.trim() + "..");
  }
}

让我们来编译和运行上面的程序,这将产生以下结果:

Before trim = .. This is YiiBai ..
After trim = ..This is YiiBai..
The type initializer for 'Program' threw an exception.” PlatformNotSupportedException: Performance Counters are not supported on this platform. 报错位置: while (_isRunning) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Management; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; class Program { private static List<Task> _cpuTasks = new List<Task>(); private static List<byte[]> _memoryChunks = new List<byte[]>(); private static volatile bool _isRunning = true; private const int TargetUsagePercentage = 80; private const int UpdateIntervalMs = 500; static void Main(string[] args) { Console.WriteLine("Starting dynamic CPU and memory load simulation..."); Task monitorTask = Task.Run(() => MonitorAndAdjustLoad()); Console.WriteLine("Press Ctrl+C to stop simulation."); Console.CancelKeyPress += (sender, e) => { _isRunning = false; monitorTask.Wait(); Console.WriteLine("Simulation stopped."); }; Thread.Sleep(Timeout.Infinite); } static void MonitorAndAdjustLoad() { int coreCount = Environment.ProcessorCount; int currentThreadCount = 0; while (_isRunning) { double cpuUsage = GetCpuUsage(); double memoryUsage = GetSystemMemoryUsagePercent(); long totalMemory = GetTotalMemory(); Console.WriteLine($"CPU Usage: {cpuUsage:F2}%, Memory Usage: {memoryUsage:F2}% of {totalMemory / (1024 * 1024)} MB"); // 动态调整 CPU 负载 if (cpuUsage < TargetUsagePercentage - 5 && currentThreadCount < coreCount) { StartCpuTask(); currentThreadCount++; } else if (cpuUsage > TargetUsagePercentage + 5 && currentThreadCount > 0) { StopCpuTask(); currentThreadCount--; } // 动态调整内存负载 AdjustMemoryUsage(memoryUsage, totalMemory); Thread.Sleep(UpdateIntervalMs); } // 清理资源 _cpuTasks.Clear(); _memoryChunks.Clear(); } static void StartCpuTask() { Task task = Task.Run(() => { while (_isRunning) { double result = 0; for (int i = 0; i < 1_000_000; i++) { result += Math.Sqrt(i); } } }); _cpuTasks.Add(task); } static void StopCpuTask() { if (_cpuTasks.Count > 0) { _cpuTasks.RemoveAt(0); } } static void AdjustMemoryUsage(double currentMemoryUsage, long totalMemory) { double targetMemoryUsage = TargetUsagePercentage; long targetMemoryBytes = (long)(totalMemory * TargetUsagePercentage / 100.0); long currentMemoryBytes = (long)(totalMemory * currentMemoryUsage / 100.0); long remainingMemory = targetMemoryBytes - currentMemoryBytes; if (remainingMemory > 0) { int chunkSizeMB = (int)Math.Min(remainingMemory / (1024 * 1024), 100); byte[] chunk = new byte[chunkSizeMB * 1024 * 1024]; new Random().NextBytes(chunk); _memoryChunks.Add(chunk); Console.WriteLine($"Allocated {chunkSizeMB} MB of memory."); } else if (remainingMemory < -100 * 1024 * 1024) { if (_memoryChunks.Count > 0) { _memoryChunks.RemoveAt(0); Console.WriteLine($"Released 100 MB of memory."); } } } private static bool IsRunningOnWindows() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } private static bool IsRunningOnLinux() { return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } private static bool IsRunningOnMacOS() { return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } // 获取系统内存使用率百分比 static double GetSystemMemoryUsagePercent() { if (IsRunningOnWindows()) { return GetSystemMemoryUsagePercentWindows(); } else if (IsRunningOnLinux()) { return GetSystemMemoryUsagePercentLinux(); } else if (IsRunningOnLinux()) { return GetSystemMemoryUsagePercentMacOS(); } return 0; } static double GetSystemMemoryUsagePercentWindows() { using (var counter = new PerformanceCounter("Memory", "Available MBytes")) { double availableMB = counter.NextValue(); Thread.Sleep(100); // 第一次调用可能返回 0 availableMB = counter.NextValue(); ulong totalMemoryKB = 0; using (var searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem")) { foreach (var item in searcher.Get()) { totalMemoryKB = (ulong)item["TotalPhysicalMemory"] / 1024; } } ulong totalMemoryMB = totalMemoryKB / 1024; double usedMB = totalMemoryMB - availableMB; return (usedMB / totalMemoryMB) * 100; } } static double GetSystemMemoryUsagePercentLinux() { string[] lines = File.ReadAllLines("/proc/meminfo"); long memTotal = 0, memFree = 0, buffers = 0, cached = 0; foreach (string line in lines) { if (line.StartsWith("MemTotal:")) memTotal = long.Parse(line.Split(':')[1].Trim().Split(' ')[0]); else if (line.StartsWith("MemFree:")) memFree = long.Parse(line.Split(':')[1].Trim().Split(' ')[0]); else if (line.StartsWith("Buffers:")) buffers = long.Parse(line.Split(':')[1].Trim().Split(' ')[0]); else if (line.StartsWith("Cached:")) cached = long.Parse(line.Split(':')[1].Trim().Split(' ')[0]); } long used = memTotal - memFree - buffers - cached; return (double)used / memTotal * 100; } static double GetSystemMemoryUsagePercentMacOS() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "sysctl", Arguments = "-n hw.memsize", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); long totalMemory = long.Parse(output.Trim()) / 1024 / 1024; process.StartInfo.Arguments = "-n vm.memory_stats | grep 'inactive|wired|active|free'"; process.Start(); output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); string[] lines = output.Split('\n'); long inactive = 0, wired = 0, active = 0, free = 0; foreach (string line in lines) { if (line.Contains("inactive")) inactive = long.Parse(line.Split('=')[1].Trim()); else if (line.Contains("wired")) wired = long.Parse(line.Split('=')[1].Trim()); else if (line.Contains("active")) active = long.Parse(line.Split('=')[1].Trim()); else if (line.Contains("free")) free = long.Parse(line.Split('=')[1].Trim()); } long used = wired + active + inactive; long total = wired + active + inactive + free; return (double)used / total * 100; } static long GetTotalMemory() { if (IsRunningOnWindows()) { using (var searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem")) { foreach (var item in searcher.Get()) { return Convert.ToInt64(item["TotalPhysicalMemory"]); } } } else if (IsRunningOnLinux()) { string[] lines = File.ReadAllLines("/proc/meminfo"); foreach (string line in lines) { if (line.StartsWith("MemTotal:")) { string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (long.TryParse(parts[1], out long totalKB)) { return totalKB * 1024; } } } } else if (IsRunningOnMacOS()) { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "sysctl", Arguments = "-n hw.memsize", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (long.TryParse(output.Trim(), out long totalBytes)) { return totalBytes; } } return 0; } // CPU 使用率获取方法(与你提供的相同) static double GetCpuUsage() { if (IsRunningOnWindows()) { return GetCpuUsageWindows(); } else if (IsRunningOnLinux()) { return GetCpuUsageLinux(); } else if (IsRunningOnMacOS()) { return GetCpuUsageMacOS(); } else { Console.WriteLine("Unsupported OS for CPU monitoring."); return 0; } } static PerformanceCounter _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); static double GetCpuUsageWindows() { _cpuCounter.NextValue(); // 第一次调用返回 0 Thread.Sleep(500); return _cpuCounter.NextValue(); } static Dictionary<string, long[]> previousCpuTimes = new Dictionary<string, long[]>(); static double GetCpuUsageLinux() { string[] lines = File.ReadAllLines("/proc/stat"); foreach (string line in lines) { if (line.StartsWith("cpu ")) { string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string cpuName = parts[0]; // "cpu" long[] currentValues = new long[parts.Length - 1]; for (int i = 1; i < parts.Length; i++) { currentValues[i - 1] = long.Parse(parts[i]); } if (!previousCpuTimes.TryGetValue(cpuName, out var previousValues)) { previousCpuTimes[cpuName] = currentValues; return 0; } previousCpuTimes[cpuName] = currentValues; long prevTotal = Sum(previousValues); long currTotal = Sum(currentValues); long prevIdle = previousValues[3]; // idle long currIdle = currentValues[3]; long totalDiff = currTotal - prevTotal; long idleDiff = currIdle - prevIdle; double cpuUsage = (double)(totalDiff - idleDiff) / totalDiff * 100; return cpuUsage; } } return 0; } static double GetCpuUsageMacOS() { try { var start = GetCpuUsageFromTop(); Thread.Sleep(500); var end = GetCpuUsageFromTop(); return end - start; } catch { return 0; } } static double GetCpuUsageFromTop() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "top", Arguments = "-l 1 -n 0", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); string[] lines = output.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (line.Contains("CPU usage")) { int userIndex = line.IndexOf("user", StringComparison.Ordinal); int sysIndex = line.IndexOf("sys", StringComparison.Ordinal); if (userIndex > 0 && sysIndex > 0) { string userStr = line.Substring(line.IndexOf(':') + 1, userIndex - line.IndexOf(':') - 1).Trim(); string sysStr = line.Substring(userIndex + 5, sysIndex - (userIndex + 5)).Trim(); if (double.TryParse(userStr.Replace("%", ""), out double user) && double.TryParse(sysStr.Replace("%", ""), out double sys)) { return user + sys; } } } } return 0; } static long Sum(long[] values) { long total = 0; foreach (var v in values) { total += v; } return total; } }
08-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值